如何解决为什么我不能在嵌套模型中更改值?
我有2类,第一类具有从第二类继承的属性
class FirstModel{
var firstType : Secondmodel?
}
class Secondmodel{
var secondType : Int?
}
现在,我想为secondType
设置一个值,以便我进行编码
var Modelll = FirstModel()
Modelll.firstType?.secondType = 100
当我尝试使用print(Modelll.firstType?.secondType)
读取此属性时,它返回nil
所以第一个问题是为什么我看不懂
但是我尝试这样做
var Modelll = FirstModel()
var ModelSecond = Secondmodel()
ModelSecond.secondType = 100
Modelll.firstType = ModelSecond
print(Modelll.firstType?.secondType)
它工作正常,已打印出来Optional(100)
,我真的不了解幕后发生了什么。谁能解释一下?
解决方法
首先,所有变量和常量都应使用小写字母命名。仅使用大写字母的类,结构,协议,枚举等名称
您的问题是,当您初始化FirstModel时,默认情况下firstType变量为nil
var model = FirstModel()
print(model.firstType) //prints nil
所以你需要做
var model = FirstModel()
model.firstType = SecondModel() //use camel case in naming
model.firstType?.secondType = 100
print(model.firstType?.secondType) // prints 100
,
Ammm ..因为您没有在第一次尝试中用实例启动firstType。 您可以添加类似的内容
class FirstModel{
var firstType : Secondmodel?
init() {
self.firstType = Secondmodel()
}
}
但这并不是应该做的事情。这不是嵌套的问题,只需要在firstyType属性中不提供值即可。
最好的情况应该是:
class Secondmodel{
var secondType : Int?
init(secondType: Int) {
self.secondType = secondType
}
}
var modelll = FirstModel()
modelll.firstType = SecondModel(secondType: 100)
您应该阅读有关OOP的更多信息。 ..and不得使用大写字母命名
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。