properties - "Cannot assign to the result of this expression"- 如何设置可选变量的属性

标签 properties swift

我有一个关于 Swift 和可选属性的问题。

假设我有以下代码:

import Foundation

class MyClass: NSObject {

    var parent: MyClass?
    var string: String?

    init() {
        super.init()

    }

}

let variable : MyClass = MyClass()
variable.string = "variable"
variable.parent?.string = "parent"

我在以下行中收到错误消息“无法分配给该表达式的结果”

variable.parent?.string = "parent"

现在,我可以通过将问号替换为感叹号来抑制此错误,据我所知,这使 Swift 假设对象将在运行时存在,但它崩溃了,因为显然没有对象。

本质上,如何在不执行“if variable.parent”之类的操作的情况下为可选变量设置属性?

最佳答案

要使用可选的,你需要使用可选的链接

let variable : MyClass = MyClass()
variable.string = "variable"
variable.parent = MyClass()
if let a = variable.parent {
   a.string = "parent"
}

或者如果你确定那里有对象你可以做

variable.parent!.string = "parent"

请注意,如果您没有初始化父级,您将得到一个错误。

关于properties - "Cannot assign to the result of this expression"- 如何设置可选变量的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24042965/

相关文章:

swift - 裁剪(至 : CGRect) doesn't crop correctly

node.js - 如何在 Node js中定义属性文件?

java - Spring:PropertyPlaceHolderConfigurer 用于设置非字符串/整数属性的值

ios - 我可以在 iOS 中以编程方式设置对象属性吗?

ios - 如何在swift中从函数中提取值

ios - 如何在 reloadData() 之后为 UITableViewCell 中的 UILabel 设置动画?

java - 在文本中添加动态部分

python - 动态向类添加属性

swift - 如何修复带有无效签名的dylib?

ios - 标题有什么不同?