Попытка сравнить числа, которые являются строками - PullRequest
0 голосов
/ 26 июня 2019

Я пытаюсь сравнить значение двух игральных карт, чтобы определить, является ли карта больше или меньше другой. Я смог сделать это в Python с использованием классов, но я хотел бы иметь возможность сделать это в Swift.

i.number возвращает «четыре» вместо 4, поэтому он не может сравнивать, потому что это строка. Появляющаяся ошибка:

значение типа 'Int' не имеет члена 'number'

if firstNine[0.number] > stack[0.number] {  
             ^ ~~~~~~
import UIKit

enum Number: Int {
    case Two = 2
    case Three = 3
    case Four = 4
    case Five = 5
    case Six = 6
    case Seven = 7
    case Eight = 8
    case Nine = 9
    case Ten = 10
    case Jack = 11
    case Queen = 12
    case King = 13
    case Ace = 14

    static var randomNumber: Number {
        return [Two , Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace][Int(arc4random_uniform(13))]

    }
}

enum Suit: String {
    case Spades = "spades"
    case Hearts = "hearts"
    case Diamonds = "diamonds"
    case Clubs = "clubs"

    static var randomSuit: Suit {
        return [Spades, Hearts, Diamonds, Clubs][Int(arc4random_uniform(4))]
    }
}

struct Card: CustomStringConvertible, Equatable {
    let number: Number
    let suit: Suit

    var description: String {
        return "\(number.rawValue) of \(suit.rawValue)"
    }

    static var randomCard: Card {
        return Card(number: Number.randomNumber, suit: Suit.randomSuit)
    }

    static func randomCards(count: Int) -> [Card] {
        guard count > 0 else {
            return []
        }
        guard count <= 52 else {
            fatalError("There only are 52 unique cards.")
        }
        let cards = randomCards(count: count - 1)
        while true {
            let card = randomCard
            if !cards.contains(card) {
                return cards + [card]
            }
        }
    }
}

func == (left: Card, right: Card) -> Bool {
    return left.number == right.number && left.suit == right.suit
}

let randomCards = Card.randomCards(count: 52)

var deck: [Card] = []
var firstNine: [Card] = []
var stack: [Card] = []




for i in randomCards {
    deck.append(i)
}

for i in 0...9 {
    firstNine.append(deck[i])

}

for i in 10...51 {
    stack.append(deck[i])
}


for i in firstNine {
    print(i.number)
}

for i in stack {
    print(i.number)
}


if firstNine[0.number] > stack[0.number] {
    print ("Lower")
    print (firstNine[0])
}
else {
    print ("wrong")
}

Ответы [ 2 ]

2 голосов
/ 26 июня 2019
enum Number: Int, CaseIterable, Comparable {
    case two = 2, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace
}

enum Suit: String, CaseIterable {
    case spades, hearts, diamonds, clubs
}

extension CaseIterable {
    static var random: Self.AllCases.Element {
        return Self.allCases.randomElement()!
    }
}

extension Card {
    static var randomCard: Card {
        return .init(number: .random, suit: .random)
    }
}

struct Card: CustomStringConvertible, Equatable, Comparable {
    let number: Number
    let suit: Suit
    var description: String {
        return "\(number) of \(suit)"
    }
}
extension Number {
    static func == (left: Number, right: Number) -> Bool {
        return left.rawValue == right.rawValue
    }
    static func < (left: Number, right: Number) -> Bool {
        return left.rawValue < right.rawValue
    }
}
extension Card {
    static func == (left: Card, right: Card) -> Bool {
        return left.number == right.number
    }
    static func < (left: Card, right: Card) -> Bool {
        return left.number < right.number
    }
    static let deck: [Card] = Suit.allCases.map { suit -> [Card] in
        Number.allCases.map { number -> Card in
            .init(number: number, suit: suit)
        }
    }.flatMap({$0})
}

let shuffledDeck = Card.deck.shuffled()
let firstNine = shuffledDeck.prefix(9)

for card in firstNine {
    print(card)
}

for card in shuffledDeck {
    print(card)
}
1 голос
/ 26 июня 2019

Я бы предложил ввести структуру Deck, чтобы обернуть массив Card s.Вы также можете заставить Card соответствовать Comparable.

Что-то вроде:

enum Number: Int, CaseIterable {
    case two = 2
    case three = 3
    case four = 4
    case five = 5
    case six = 6
    case seven = 7
    case eight = 8
    case nine = 9
    case ten = 10
    case jack = 11
    case queen = 12
    case king = 13
    case ace = 14

    static func random() -> Number {
        return Number.allCases.randomElement()!
    }
}

enum Suit: String, CaseIterable {
    case spades = "spades"
    case hearts = "hearts"
    case diamonds = "diamonds"
    case clubs = "clubs"

    static func random() -> Suit {
        return Suit.allCases.randomElement()!
    }
}

struct Card: CustomStringConvertible, Equatable, Comparable {

    let number: Number
    let suit: Suit

    var description: String {
        return "\(number) of \(suit)"
    }

    static func == (left: Card, right: Card) -> Bool {
        return left.number == right.number && left.suit == right.suit
    }

    static func < (lhs: Card, rhs: Card) -> Bool {
        return lhs.number.rawValue < rhs.number.rawValue
    }
}

struct Deck {

    let cards: [Card]

    init() {

        var cards = [Card]()
        for suit in Suit.allCases {
            for value in Number.allCases {
                cards.append(Card(number: value, suit: suit))
            }
        }

        self.cards = cards
    }

    private init(cards: [Card]) {
        self.cards = cards
    }

    func shuffled() -> Deck {
        return Deck(cards: self.cards.shuffled())
    }

    func cut(size: Int) -> (Deck,Deck) {
        if size < 1 {
            return (Deck(cards: []),self)
        }

        if size > self.cards.count {
            return (self,Deck(cards:[]))
        }

        return (Deck(cards: Array(self.cards[..<size])),Deck(cards: Array(self.cards[size...])))
    }
}

let randomCards = Deck().shuffled()


let cut = randomCards.cut(size: 9)
let firstNine = cut.0
let remainder = cut.1

print(firstNine.cards[0])
print(remainder.cards[0])

if firstNine.cards[0] > remainder.cards[0] {
    print("Higher")
} else {
    print("Not higher")
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...