Swift错误 - 在类型上使用实例成员

时间:2016-05-02 11:46:21

标签: swift methods struct

以下代码给出了错误:"使用实例成员' getRandomBoy' on snips ..."。

我想使用方法' getRandomBoy'在' snipArray'内部。

这可能吗?

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]
}
}

1 个答案:

答案 0 :(得分:1)

您需要在staticfunction声明之前编写variables关键字来访问内部方法。

以下是您的修改后代码:

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]
    }
}

希望这有帮助!