gpt4 book ai didi

arrays - 如何使用 Swift 递增地轮换数组?

转载 作者:行者123 更新时间:2023-11-28 13:22:13 33 4
gpt4 key购买 nike

刚刚学习 swift 并且想像这样旋转一系列颜色:

class ColorSwitcher
{
let colors:String[] = ["red", "blue", "green"]
var currIndex:Int?

var selectedColor:String{
return self.colors[currIndex!]
}

init(){
currIndex = 0
}

func changeColor()
{
currIndex++ //this doesn't work
}
}

当我尝试像这样调用函数时:

var switcher:ColorSwitcher = ColorSwitcher()
switcher.selectedColor // returns red

switcher.changeColor()

switcher.selectedColor // still returns red

问题出在 changeColor 函数上。我得到的错误是:

Could not find an overload for '++' that accepts the supplied arguments

我做错了什么?

最佳答案

问题是 currIndex 是可选的。我建议像这样重构:

class ColorSwitcher {
let colors:String[] = ["red", "blue", "green"]
var currIndex:Int = 0

var selectedColor:String {
return self.colors[currIndex]
}

func changeColor() {
currIndex++
}
}

如果你想让它成为可选的,你需要这样做:

currIndex = currIndex! + 1

但这当然不安全,所以您可能应该这样做:

if let i = currIndex {
currIndex = i + 1
}
else {
currIndex = 1
}

此外,请记住,如果您要在 init() 中设置值,则不需要使用可选项。以下是好的:

class ColorSwitcher {
let colors:String[] = ["red", "blue", "green"]
var currIndex:Int

init(startIndex: Int) {
currIndex = startIndex
}

var selectedColor:String {
return self.colors[currIndex]
}

func changeColor() {
currIndex++
}
}

关于arrays - 如何使用 Swift 递增地轮换数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24247551/

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