【问题标题】:How do I incrementally rotate through an array with Swift?如何使用 Swift 增量旋转数组?
【发布时间】:2014-06-16 15:47:21
【问题描述】:

刚刚学习 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

我做错了什么?

【问题讨论】:

    标签: arrays swift


    【解决方案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++
        }
    }
    

    【讨论】:

    • 也许currIndex = (currIndex + 1) % colors.count
    • @ChristianDietrich 确实,但这是一个单独的问题,我觉得这段代码被删减以澄清问题(因为它没有明显的用处)
    • 只是练习使用 UIKit 来旋转一系列图像:)
    • @AmitErandole 啊,是的 - 在这种情况下你不需要调用它,因为你没有超类(现已修复)
    【解决方案2】:

    您可以为可选的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 中所做的一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2015-06-16
      相关资源
      最近更新 更多