Search code examples
swiftintclosuresuint8t

'Int' is not identical to 'UInt8' in closure


I am trying to create a closure that keeps a reference to the local variable of the outer function and I keep getting this ambigious error int is not identical to unint8. It does not make sense to me because there no arrays involved here. There are also no UInt8s involved here too.

func increment(n:Int)-> ()->Int {
    var i = 0
    var incrementByN = {
        () -> Int in
        i += n
    }
    return incrementByN
}
var inner = increment(4)
inner()
inner()
inner()

I found that I can fix this by returning i after i+=n. I thought that i+=n would return on it's own but apparently it does not.


Solution

  • Not sure what the UInt8 is about, but it seems that += does not have a value.

    var i = 1;
    let x = i += 3;  // now x is of type () 
    

    You can explicitly return the new value of i:

    var incrementByN = {
        () -> Int in
        i += n
        return i
    }