Search code examples
swiftoption-type

Variable 'xxx' was never mutated, consider changing to 'let'


Updated to xcode7-beta I run across a new kind of warning. Here is my code

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var attributes: [UICollectionViewLayoutAttributes]? = super.layoutAttributesForElementsInRect(rect)
    if let layoutInfo = self.layoutInfo {
        attributes?.append(layoutInfo)
    }
    return attributes
}

the warning message is Variable 'attributes' was never mutated, consider changing to 'let' constant

Why does xcode say Variable 'attributes' was never mutated?

Question Update

the warning is gone when I change my code to this

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var attributes: [UICollectionViewLayoutAttributes]? = super.layoutAttributesForElementsInRect(rect)
    if let layoutInfo = self.layoutInfo {
        attributes!.append(layoutInfo)
    }
    return attributes
}

so forced unwrapping can take it away. But it might not be a good thing right?


Solution

  • They talked about this in the WWDC videos and the release notes.

    It has always been the case that you get much, much better performance (faster speed, smaller space) if you use let instead of var whenever you can. This tells the compiler that this thing is a constant, not a variable, and that fact allows the compiler to optimize all kinds of things away.

    But the compiler can't do that unless you do use let whenever you can. It won't change a var to a let for you.

    Therefore, in Swift 2, the compiler does a smarter analysis at build time and warns you if you are using var where you could have used let. Eventually this feature will work properly, at which point you should take the compiler's advice!