以下代码给出了错误:"使用实例成员' 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]
}
}
答案 0 :(得分:1)
您需要在static
和function
声明之前编写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]
}
}
希望这有帮助!