Swift意外错误无法分配给''在' self'

时间:2014-12-18 09:08:42

标签: ios swift

我有一个颜色数组,我试图从中获取一个随机颜色而没有连续获得相同的两种颜色,并且遇到previousNumber = randomNumber的错误说不能在'self'中分配给'previousNumber'

var previousNumber: UInt32?

    func generateRandomNumber() -> Int {
        var coloursArrayLength = UInt32(coloursArray.count)
        var randomNumber = arc4random_uniform(coloursArrayLength)
        while previousNumber == randomNumber {
            randomNumber = arc4random_uniform(coloursArrayLength)
        }
        previousNumber = randomNumber
        var randomNumberInt = Int(randomNumber)
        return randomNumberInt
    }

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

我猜你的函数实际上是在代码片段中没有显示的结构体内,问题是你没有将函数声明为mutating(即只能在用{let声明的结构上调用该函数。 {1}}不var,因为它会改变自我。)

为了清晰起见,我还建议将生成随机数的逻辑分解为单独的函数,并减少需要var

func generateRandom(#upTo: UInt32, #notRepeatOf: UInt32?) -> UInt32 {
    // bear in mind though that you might need to handle if your coloursArray has one entry...
    precondition(upTo > 1 || notRepeatOf == nil , "avoid infinite loop")
    while true {
        let candidate = arc4random_uniform(upTo)
        if candidate != notRepeatOf { return candidate }
    }
}

struct S {
    var previousNumber: UInt32? = nil
    let coloursArray = [1,2,3,4]

    // note mutating keyword, fixes the "cannot
    // assign to self.previousNumber" error
    mutating func generateRandomNumber() -> Int {
        let newNumber = generateRandom(upTo: UInt32(coloursArray.count), notRepeatOf: previousNumber)
        previousNumber = newNumber
        return Int(newNumber)
    }
}

// if you declare the struct with let,
let a = S()
// it won’t let you call mutating funcs
// "Immutable value of type 'S' only has mutating members named 'generateRandomNumber'"
a.generateRandomNumber()

// have to declare with var
var b = S()
b.generateRandomNumber()