从swift中的struct调用方法 [英] calling method from struct in swift
问题描述
我发现这里有一个优雅的方法来迭代枚举:如何枚举带有String类型的枚举?
I found what looks like an elegant solution to iterating over enums here: How to enumerate an enum with String type?
接下来,我无法弄清楚如何调用此方法。在面值方面,它看起来不像一个参数,但是当我尝试调用Card.createDeck()时,我得到一个编译器错误告诉我错误:参数#1在调用中缺少参数。
Next, I'm having trouble figuring out how to call this method. At face value, it doesn't look like it takes an argument, but when I try to call Card.createDeck() I get a compiler error telling me "error: missing argument for parameter #1 in call".
请让我知道我在这里做错什么?我应该传递给这个方法?
Please let me know what I'm doing wrong here? What am I supposed to pass to this method?
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
func createDeck() -> [Card] {
var deck = [Card]()
var n = 1
while let rank = Rank.fromRaw(n) {
var m = 1
while let suit = Suit.fromRaw(m) {
deck += Card(rank: rank, suit: suit)
m++
}
n++
}
return deck
}
}
推荐答案
createDeck()
是一个实例方法。执行 Card.createDeck()
是对不存在的类方法的调用。
createDeck()
is a instance method. Doing Card.createDeck()
is a call to a class method that doesn't exist.
class func
- 类方法
编辑:
我误读它是一个结构体,但是相同的逻辑适用。
I misread that it was a struct, but the same logic applies.
static func
- 用于静态方法
static func
- for static methods
这篇关于从swift中的struct调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!