Swift:为什么这是不可变的?

Swift: Why is this immutable?

你能告诉我为什么这段代码不起作用吗?

我有几个包含 UILabel 和 UITextForm 的 [AnyObject] 数组。 此 func 应将数组作为参数并禁用所有标签和文本表单。我试过使用地图,但我仍然遇到同样的问题,编译器告诉我或者变量是常量或者是不可变的。

func disableSectionForm(formSection section: inout [AnyObject]) {
    for i in 0...section.count {
        if section[i] is UILabel || section[i] is UITextField {
            section[i].isEnabled = false
        }
    }
}

尝试检查 let 是否阻塞并使用选项

func disableSectionForm(formSection section: inout [AnyObject]) {
            for i in 0...section.count {
                if let label = section[i] as? UILabel {
                     label.isEnabled = false
                }
                if let textField = section[i] as? UITextFiled {
                     textField.isEnabled = false
                }
            }
 }

这里有很多编译错误

问题 #1(这只是一个建议)

inout 在这里不需要,因为您没有改变 section 数组,而是改变其中的对象。

第 2 期

inout 应该放在参数名称之前(如果您使用的是 Swift 2.2)

第 3 期

与 dynamicType

比较时应使用 self

第 4 期

你不能写section[i].isEnabled = false因为AnyObject没有成员isEnabled所以你应该做一个转换

第 5 期

您正在访问数组外的索引,因此

0...section.count

应该变成这样

0..<section.count

代码版本 #1

现在你的代码看起来像这样

func disableSectionForm(formSection section: [AnyObject]) {
    for i in 0..<section.count {
        if section[i].dynamicType == UILabel.self {
            (section[i] as? UILabel)?.enabled = false
        } else if section[i].dynamicType == UITextField.self {
            (section[i] as? UITextField)?.enabled = false
        }
    }
}

代码版本 #2

开始于:

  1. 您可以以更安全的方式迭代元素
  2. 你应该使用 conditional cast 而不是 dynamicType comparation

你可以写在

Swift 2.2

func disableSectionForm(formSection section: [AnyObject]) {
    section.forEach {
        switch [=13=] {
        case let label as UILabel: label.enabled = false
        case let textField as UITextField: textField.enabled = false
        default: break
        }
    }
}

Swift 3.0 (beta 6)

func disableSectionForm(formSection section: [Any]) {
    section.forEach {
        switch [=14=] {
        case let label as UILabel: label.isEnabled = false
        case let textField as UITextField: textField.isEnabled = false
        default: break
        }
    }
}

代码版本 #3

让我们定义一个协议来表示 类 和 enabled Bool 属性.

Swift 2.2

protocol HasEnabledProperty:class {
    var enabled: Bool { get set }
}

让我们符合它UILabelUITextLabel

extension UILabel: HasEnabledProperty { }
extension UITextField: HasEnabledProperty { }

最后...

func disableSectionForm(formSection section: [AnyObject]) {
    section.flatMap { [=17=] as? HasEnabledProperty }.forEach { [=17=].enabled = false }
}

Swift 3.0 (beta 6)

protocol HasEnabledProperty:class {
    var isEnabled: Bool { get set }
}

extension UILabel: HasEnabledProperty { }
extension UITextField: HasEnabledProperty { }

func disableSectionForm(formSection section: [Any]) {
    section.flatMap { [=18=] as? HasEnabledProperty }.forEach { [=18=].isEnabled = false }
}