Ios 为什么我能';不改变嵌套模型中的值?
我有两个类,第一个类有一个从第二个类继承的属性Ios 为什么我能';不改变嵌套模型中的值?,ios,swift,model,nested,Ios,Swift,Model,Nested,我有两个类,第一个类有一个从第二个类继承的属性 class FirstModel{ var firstType : Secondmodel? } class Secondmodel{ var secondType : Int? } 现在我想将一个值设置为secondType,这样我就可以编码了 var Modelll = FirstModel() Modelll.firstType?.secondType = 100 当我尝试使用print(modell.firstT
class FirstModel{
var firstType : Secondmodel?
}
class Secondmodel{
var secondType : Int?
}
现在我想将一个值设置为secondType
,这样我就可以编码了
var Modelll = FirstModel()
Modelll.firstType?.secondType = 100
当我尝试使用print(modell.firstType?.secondType)
读取此属性时,它返回nil
第一个问题是为什么我看不懂这个
但我试着这么做
var Modelll = FirstModel()
var ModelSecond = Secondmodel()
ModelSecond.secondType = 100
Modelll.firstType = ModelSecond
print(Modelll.firstType?.secondType)
它工作得很好,打印出来的
可选(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
嗯。。因为您在第一次尝试时没有使用实例启动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的内容。
..并且对象不应使用大写字母命名在第一种情况下,您没有初始化firstType,而是直接为其指定了一个值,即nil和nil