只是学习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
我做错了什么?
答案 0 :(得分:1)
问题是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++
}
}
答案 1 :(得分:1)
您可以为可选的++
重载缺少的Int
运算符,例如这样:
@assignment @postfix func ++(inout x: Int?) -> Int? {
if x != nil {
x = x! + 1
return x
} else {
return nil
}
}
或者您可以更改您的课程,例如这样:
class ColorSwitcher {
let colors:String[] = ["red", "blue", "green"]
var currIndex: Int = 0
var selectedColor: String {
return self.colors[currIndex]
}
func changeColor() {
currIndex++
}
}
注意:这对您班级的内部行为没有任何改善。它会像你在OP中那样做。