Heinevolder
Heinevolder

Reputation: 338

Swift error - Use of instance member on type

Following code gives me error: "Use of instance member 'getRandomBoy' on type Snips...".

I would like to use the method 'getRandomBoy' inside of the 'snipArray'.

Is this possible?

Import Darwin

struct Snips {

let boyNames: [String]

let snipArray: [String] = [
    "Drink A beer",
    "Drink yet another Beer",
    "Drink 4 beers",
    "\(getRandomBoy()) has to drink)"
    ]

func getRandomSnip() -> String{
    let randomNumber: Int = Int(arc4random_uniform(UInt32(snipArray.count)))
    return snipArray[randomNumber]
}

func getRandomBoy() -> String{
    let randomNumber: Int = Int(arc4random_uniform(UInt32(boyNames.count)))
    return boyNames[randomNumber]
}
}

Upvotes: 0

Views: 921

Answers (1)

Sohel L.
Sohel L.

Reputation: 9540

You need to write static keyword before function and variables declaration to access inside methods.

Here is the modified code of yours':

struct Snips {

    static let boyNames = ["Hi", "Hello"]

    static let snipArray: [String] = [
        "Drink A beer",
        "Drink yet another Beer",
        "Drink 4 beers",
        "\(Snips.getRandomBoy()) has to drink)"
    ]

    static func getRandomSnip() -> String{
        let randomNumber: Int = Int(arc4random_uniform(UInt32(snipArray.count)))
        return snipArray[randomNumber]
    }

    static func getRandomBoy() -> String{
        let randomNumber: Int = Int(arc4random_uniform(UInt32(boyNames.count)))
        return boyNames[randomNumber]
    }
}

Hope this helps!

Upvotes: 1

Related Questions