【发布时间】:2015-06-10 03:21:32
【问题描述】:
更新到 xcode7-beta 我遇到了一种新的警告。这是我的代码
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes: [UICollectionViewLayoutAttributes]? = super.layoutAttributesForElementsInRect(rect)
if let layoutInfo = self.layoutInfo {
attributes?.append(layoutInfo)
}
return attributes
}
警告信息是
Variable 'attributes' was never mutated, consider changing to 'let' constant
xcode 为什么说Variable 'attributes' was never mutated?
问题更新
当我将代码更改为此时,警告消失了
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes: [UICollectionViewLayoutAttributes]? = super.layoutAttributesForElementsInRect(rect)
if let layoutInfo = self.layoutInfo {
attributes!.append(layoutInfo)
}
return attributes
}
所以强制解包可以把它拿走。但这未必是件好事吧?
【问题讨论】:
-
您是否尝试更改为让?还能编译吗?
-
嗨@Icaro 我需要附加我的 layoutInfo 所以我真的需要一个 var
-
所以一定是编译器的bug!
-
我倾向于认为在这种特定情况下这可能是一个错误。在 iOS 9 SDK 中,许多 Cocoa Touch 类已经过审核以支持 Objective-C 泛型,编译器可能会将这些新类型的 NSArray 与类型化的 Swift 数组混淆。此处使用 var 提供了使用 let 的建议,但使用 let 会产生错误。
-
看起来像一个错误。使用
attributes!.append(layoutInfo)而不是attributes?.append(layoutInfo),警告消失:)