swift - swift 4 weak variable
问题描述
In below code, why when car1 variable was assigned nil , car2 is not nil? Can someone explain it?.I am asking this question because of that I know when all strong references of a object was assigned nil , all other weak references are assigned nil automatically.is it wrong?
Thank you so much.
class ViewController: UIViewController {
var car1 : Car? = Car()
weak var car2 : Car?
override func viewDidLoad() {
super.viewDidLoad()
car2 = car1
car1 = nil
print("gfehtre")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
解决方案
Not sure what your question is: car2
is not nil only when car2 = car1
is executed on the next line car1 = nil
car2
also becomes nil,
Test it yourself by:
override func viewDidLoad() {
super.viewDidLoad()
if let _ = car2 {
print("first")
}
car2 = car1
if let _ = car2 {
print("second")
}
car1 = nil
if let _ = car2 {
print("third")
}
}
You will see in console that only second
is printed in all other cases car2
is nil
推荐阅读
- java - Spring Boot是否可以将接口的实现绑定到@ConfigurationProperties
- c# - 使用 C# 如何将此字符串解析为时间
- c# - ASP.NET Core 3.1 中 API 控制器的单元测试返回错误的状态代码
- sql-server - 获取组中的最新行
- python - 我如何克服这个问题,模型适合 python
- java - java: 使用 stream.forEach() 或 stream.forEachOrdered() 将东西放入集合
- msbuild - 使用 msbuild 和 TeamCity 构建 nuget .Net Framework Web 应用程序包?
- oracle - Oracle PSQL 在 with as 表达式中获取错误原因
- reactjs - JSX Fragment 只是说,将它们作为最后一个兄弟姐妹添加到父母中,这是真的吗?
- reactjs - 在 React 组件中通过 onMouseEnter 设置延迟状态