Page 37 of The Swift Programming Language: func works in code but not as method of a struct -
i'm trying exercise page 37 of swift programming language book apple here's struct 2 enums (from swift programming reference):
struct card { var rank: rank var suit: suits func description() -> string { return "the \(rank.ofrank()) of \(suit.ofsuit())" } func createdeck() -> (card[]){ var deck = card []() rangeofsuits in 1...4 { rangeofranks in 1...13 { println("\(rangeofranks)") deck.append(card(rank: rank.fromraw(rangeofranks)!, suit: suits.fromraw(rangeofsuits)!)) } } return (deck) } }
that second method: createdeck() doesn't work. when used
mydeck.createdeck()
gives compile error: "card() not have member 'createdeck'" however, remove struct , works fine:
func createdeck () -> (card[]){ var deck = card []() rangeofsuits in 1...4 { rangeofranks in 1...13 { deck.append(card(rank: rank.fromraw(rangeofranks)!, suit: suits.fromraw(rangeofsuits)!)) } } return (deck) } mydeck = createdeck() mydeck.count //yields 52, should mydeck[51].description() //yields king of clubs should.
my answer question is: on page 384 of swift programming language:
“type methods instance methods, described above, methods called on instance of particular type. can define methods called on type itself. these kinds of methods called type methods. you indicate type methods classes writing keyword class before method’s func keyword, , type methods for structures , enumerations writing keyword static before method’s func keyword.”
i not clear on why 1 has this, method works when add "static" in front of , fails when don't.
mydeck.createdeck()
makes no sense because have no card. struct class; send instance method it, need instance. instantiate first:
var mydeck = card() // not really, though mydeck.createdeck()
however, that code won't work either, because ()
not valid initializer card. replace first line actual initializer.
Comments
Post a Comment