403_intermediate_swift
00 分钟
WWDC Year
2014
Topic
Swift
Watched
2
Tags
Memory Managerment
Pattern Matching
Closure
MOV
MOV
MOV Date
PDF
PDF
PDF Date
Transcript
Transcript
Transcript Date
Github
Finish
Status
Week
Note

What You Will Learn

Optionals
Memory management
Initialization
Closures
Pattern matching
 

Optionals

Optional Chaining
notion image
 
Optionals Under the Hood
 
Use optionals to safely work with possibly missing values
  • Missing values are nil
  • Present values are wrapped in an optional
Unwrap an optional to access its underlying value
  • Use the forced-unwrapping operator (!) only if you are sure
  • Use if let optional binding to test and unwrap at the same time
Optional chaining (?) is a concise way to work with chained optionals
 

Memory management

 
Automatic Reference Counting
notion image
notion image
notion image
notion image
notion image
 
Ownership
notion image
notion image
notion image
 
 
 
Weak References
notion image
notion image
notion image
 
 
‼️Using Weak References
Weak references are optional values
Binding the optional produces a strong reference
Testing a weak reference alone does not produce a strong reference
Chaining doesn't preserve a strong reference between method invocations
 
Unowned References
 
 
Chatgpt关于如何使用的unownedweak
理解何时使用unowned和何时使用weak主要取决于你对引用对象生命周期的了解以及在引用对象释放后的处理方式。下面提供一些建议:

使用 unowned 当:

  1. 生命周期明确: 你能够确定引用对象的生命周期始终长于引用它的对象。这样,你就可以确保在访问时引用对象仍然存在。
  1. 不会变为 nil 你能够确保在访问时引用对象不会被释放。使用unowned的前提是你可以保证引用对象不会在被引用对象之前被释放,否则会导致运行时崩溃。
  1. 避免可选类型: 你希望引用是非可选类型,而不想在每次访问时检查是否为nil
在这个例子中,BookAuthor的引用是unowned,因为书始终关联着一个作者,而且书的生命周期不会超过作者。

使用 weak 当:

  1. 生命周期不确定: 你无法确定引用对象何时会被释放,或者引用对象的生命周期可能比引用它的对象短。
  1. 需要可选类型: 你希望引用是可选类型,以便在引用对象被释放后自动变为nil,而不导致崩溃。
在这个例子中,EmployeeDepartment的引用是weak,因为员工可能在没有部门的情况下存在,而且部门的生命周期可能短于员工。
总体来说,如果你能确定引用对象的生命周期,而且能够确保在访问时它仍然存在,可以选择使用 unowned。如果生命周期不确定或需要可选类型,使用 weak
 
 
 

Initialization

 

Closures

 

Pattern matching