Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swift - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...