gpt4 book ai didi

arrays - 快速 array.removeAtIndex 错误

转载 作者:行者123 更新时间:2023-11-30 10:12:13 25 4
gpt4 key购买 nike

为什么我收到错误“NSArray 没有名为“removeAtIndex”的成员。我该如何解决这个问题?错误位于倒数第四行。抱歉,如果我的问题很愚蠢,我是新手编程。我感谢我得到的所有帮助。

import Foundation
let userDefaults = NSUserDefaults.standardUserDefaults()

func isAppAlreadyLaunchedOnce()->Bool{
let defaults = NSUserDefaults.standardUserDefaults()

if let isAppAlreadyLaunchedOnce = defaults.stringForKey("isAppAlreadyLaunchedOnce"){
println("App already launched")
return true
}
else{
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
println("App launched first time")
return false
}
}

struct newFactBook {


let factsArray = [
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built."]

}

var checkLaunch = isAppAlreadyLaunchedOnce()
var oldFunFactsArray = []

if(checkLaunch == false){
oldFunFactsArray = newFactBook().factsArray
}

else if (checkLaunch == true){
oldFunFactsArray = userDefaults.objectForKey("key") as! NSArray
}




func randomFacts1() -> (String, Int){
var unsignedArrayCount = UInt32(oldFunFactsArray.count)
var unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
var randomNumber = Int(unsignedRandomNumber)
return (oldFunFactsArray[randomNumber] as! String, randomNumber)

}


oldFunFactsArray.removeAtIndex[randomFacts1().1] //error here

userDefaults.setObject(oldFunFactsArray, forKey:"key")
userDefaults.synchronize()
println(oldFunFactsArray)

最佳答案

我们这里遇到一些问题:

1 如何调用方法

removeAtIndex 是一个接受 Int 作为参数的方法。它不能以这种方式调用

removeAtIndex[randomFacts1().1]

相反,你应该写

removeAtIndex(randomFacts1().1)

2。 oldFunFactsArray 的类型是 NSArray,这是错误的。

当你写下这个时完好无损:

var oldFunFactsArray = []

Swift 确实推断出这一点:

var oldFunFactsArray : NSArray = []

但是此时您有一个不可变NSArray,因此它没有removeAtIndex方法。

由于您使用的是 Swift,我建议您按如下方式声明 var oldFunFactsArray:

var oldFunFactsArray : [String]

if checkLaunch == false {
oldFunFactsArray = newFactBook().factsArray
} else {
oldFunFactsArray = userDefaults.objectForKey("key") as! [String]
}

请注意,我在这里声明了一个 Swift 字符串数组。由于我使用 var 关键字,该数组将可变,稍后我们将能够调用 removeAtIndex

Also note that in the else branch I am force-casting the result of objectForKey to [String]. It will be fine since I see, below, you are writing the oldFunFactsArray in that slot.

希望这有帮助。

关于arrays - 快速 array.removeAtIndex 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334706/

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