所以我一直在做Apple Swift Book中的实验。
除了到目前为止,我已经能够完成所有这些操作。下面是我尝试过的方法,但是我不知道如何使它工作。
向 Card 添加一种方法,以创建一副完整的纸牌,其中每个等级和花色组合都有一张纸牌。
// Playground - noun: a place where people can play enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } } enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } func createFullDeck() -> Array{ var FullDeck: Array FullDeck = Card(rank: .Ace, suit: .Spades) FullDeck = Card(rank: .Two, suit: .Spades) return FullDeck } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() threeOfSpades.createFullDeck()
threeOfSpades.createFullDeck()
这是另一种实现方式,这一次仅使用您到目前为止所学的技术*
首先,我们使用先前定义的枚举Rank和Suit枚举定义可能的等级和花色。
Rank
Suit
接下来,我们具有对每个西装中的每个等级进行迭代的功能,为每个西装创建一张卡片,最后返回一系列卡片。
struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } func createDeck() -> [Card] { let ranks = [Rank.ace, Rank.two, Rank.three, Rank.four, Rank.five, Rank.six, Rank.seven, Rank.eight, Rank.nine, Rank.ten, Rank.jack, Rank.queen, Rank.king] let suits = [Suit.spades, Suit.hearts, Suit.diamonds, Suit.clubs] var deck = [Card]() for suit in suits { for rank in ranks { deck.append(Card(rank: rank, suit: suit)) } } return deck } }
(*值得注意的例外是,导览当时没有明确说明如何附加到数组)