Implicitly unwrapped optional made immutable

后端 未结 2 585
盖世英雄少女心
盖世英雄少女心 2020-12-06 11:22

Why is it that I cannot mutate an implicitly unwrapped optional variable?

Here is a short example the reproduces the issue:

With Array

var          


        
2条回答
  •  借酒劲吻你
    2020-12-06 12:18

    Update:

    This has been fixed in Xcode Beta 5 with one small caveat:

    var list: [Int]! = [1]
    list.append(10)
    
    var number: Int! = 1
    number! += 2
    number += 2 // compile error
    

    The array works as expected, but it seems that right now the integer still requires an explicit unwrap to allow using +=


    Currently, this is just the nature of Optionals (whether implicitly unwrapped or not). The unwrap operator returns an immutable value. This is likely to be fixed or a better solution will be provided in the future.

    The only way around it for now is to wrap the array in a class:

    class IntArray {
        var elements : [Int]
    }
    

提交回复
热议问题