在iOS中使用NSMutableAttributedString作为常量

时间:2015-02-22 00:32:51

标签: ios swift nsstring constants

我刚开始学习斯威夫特并遇到了一些我不理解的东西。在教程中,作者在常量中创建NSMutableAttributedString。后来,这个常数被改变了。我不明白的是,如果没有任何错误,这是可能的。 NSMutableAttributedString以某种方式,由于缺少更好的术语,会覆盖常量的规则吗?

@IBAction func buttonPressed(sender: UIButton) {
    let title = sender.titleForState(.Normal)!
    let plainText = "\(title) button pressed"
    let styledText = NSMutableAttributedString(string: plainText)
    let attributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(statusLabel.font.pointSize)]
    let nameRange = (plainText as NSString).rangeOfString(title)
    styledText.setAttributes(attributes, range: nameRange)

    statusLabel.attributedText = styledText
}

1 个答案:

答案 0 :(得分:1)

它与NSMutableAttributedString无关,但与styledText存储引用类型的事实有关。由于它被定义为常量,因此您无法更改其值:

styledText = NSMutableAttributedString(string: "anotherString") // Error

但您可以对变量指向的实例进行更改。

Swift中的let关键字强制实现值类型(结构和枚举)的不变性,而不是引用类型。

Swift中的结构和枚举有两种方法:

  • 使用关键字mutating
  • 定义的变异方法
  • 非变异方法(默认行为)

如果将结构或枚举的实例分配给可变存储(使用var定义的内容),则可以通过调用任何变异或非变异方法来自由地修改它的状态。它

如果将其分配给不可变存储(使用let定义),则只能在其上调用非变异方法。您也不能使存储存储器成为另一个实例(即,您不能为其分配另一个结构或枚举)。

作为引用类型的类没有变异或非变异方法的概念。