【问题标题】:Swift struct item value not changing with functionSwift struct item 值不随函数变化
【发布时间】:2018-06-18 23:37:19
【问题描述】:

我有下面的代码,但即使将函数 newMethod(newName: String) 添加到类中,username 的值对于变量 user 也不会改变。 Profile 结构在不同的类中定义。我究竟做错了什么?注意:我使用的是 LBTAComponents pod。

import LBTAComponents

class ProfileDatasource: Datasource {
    let placeholderIV: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()

    var user = Profile(username: String(), school: "fat", rating: 48, friends: 73, posts: 98, docs: 3, bioText: "Hi I'm a sophomore from Cyprus Bay and can help with most fields relating to high school math.", profileImage: UIImageView(), bgImage: UIImageView())

    func newThing(newName: String) {
        let newName = "Hi"
        print(newName)
        ProfileDatasource().user.username = newName
    }
}

【问题讨论】:

  • 请注意,您的 newName 局部变量隐藏了您的 newName 参数。
  • 不相关但将String() 替换为""

标签: swift function struct


【解决方案1】:

这一行

ProfileDatasource().user.username = newName

主要通过这个ProfileDatasource()创建一个新的var,你需要

self.user.username = newName

【讨论】:

  • 对不起,这似乎也不起作用:(谢谢
【解决方案2】:

在您尝试改变 username 属性的行中,您是

  1. 创建一个全新的ProfileDatasource 对象
  2. 从新的ProfileDatasource 获取user 属性
  3. username 设置为newName

之后,您的新 ProfileDatasource 将被解除分配,并且没有任何实际变化。如果你想改变 user 属性,你可以省略新对象的创建,像这样:

user.username = newName

【讨论】:

  • 对不起,这似乎也不起作用:(谢谢
  • 这绝对是解决方案的至少一部分。你在做什么,你期望发生什么,实际发生了什么?
  • @EthanWilk 将此答案与我在您的问题下方发布的评论结合起来。
猜你喜欢
  • 1970-01-01
  • 2013-06-21
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 2022-06-13
  • 1970-01-01
相关资源
最近更新 更多