【问题标题】:How do you assign a string value to a property in another class in Swift?如何在 Swift 中为另一个类中的属性分配字符串值?
【发布时间】:2014-06-13 14:08:46
【问题描述】:

我有一些看起来像这样的快速代码:

class GeoRssItem
{
    var title = ""
    var description = ""
}

在另一个类中,我将这个变量声明为:

var currentGeoRssItem : GeoRssItem?    // The current item that we're processing

我将此成员变量分配为:

        self.currentGeoRssItem = GeoRssItem();

然后当我尝试在 self.currentGeoRssItem Xcode 上分配一个属性时,自动完成:

        self.currentGeoRssItem.?.description = "test"

然后失败并出现构建错误:

"Expected member name following '.'"

如何设置此属性?我已经阅读了文档,但它们不是很有帮助。

【问题讨论】:

    标签: swift


    【解决方案1】:

    问号放错地方了。应该是:

    self.currentGeoRssItem?.description = "test"
    

    但是你可能会得到:"Cannot assign to the result of this expression"。 在这种情况下,您需要像这样检查 nil:

    if let geoRssItem = self.currentGeoRssItem? {
        geoRssItem.description = "test"
    }
    

    【讨论】:

    • 是的; “...您可以使用可选链接访问可选值的属性,并检查该属性访问是否成功。 但是,您不能通过可选链接设置属性的值。” — Swift 编程语言,“可选链”。
    【解决方案2】:

    如果你想断言这个值是非零的,你可以这样做:

    self.currentGeoRssItem!.description = "test"
    

    如果变量为 nil 时,如果您希望语句为空操作,则

    self.currentGeoRssItem?.description = "test"
    

    【讨论】:

    • 该!有效,但使用 ?导致错误“无法分配给此表达式的结果”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多