user3815911
user3815911

Reputation:

calling method from struct in swift

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
    }

}

Upvotes: 8

Views: 13507

Answers (2)

codester
codester

Reputation: 37189

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.

Upvotes: 3

Literphor
Literphor

Reputation: 498

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

Upvotes: 14

Related Questions