gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:04:08 24 4
gpt4 key购买 nike

以下代码给出错误:“在 Snips 类型上使用实例成员“getRandomBoy”...”。

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

这可能吗?

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

最佳答案

您需要在functionvariables声明之前编写static关键字才能访问内部方法。

这是您修改后的代码:

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

希望这有帮助!

关于Swift 错误 - 在类型上使用实例成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com