calling method from struct in swift

风流意气都作罢 提交于 2019-12-10 17:35:15

问题


I found what looks like an elegant solution to iterating over enums here: How to enumerate an enum with String type?

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
    }

}

回答1:


createDeck() is a instance method. Doing Card.createDeck() is a call to a class method that doesn't exist.

class func - for class methods

Edit:

I misread that it was a struct, but the same logic applies.

static func - for static methods




回答2:


You can not able to call it directly as you need instace of struct as it is not class function.So use

Card(rank:Rank.yourRank,suit:Suit.yourSuit).createDeck()

Actually to make struct you need rank and suit instance so first make them and than pass to Card constructor.By default struct have arguments as their properties.



来源:https://stackoverflow.com/questions/25046226/calling-method-from-struct-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!