当前位置:网站首页>Swift initializer and optional chain
Swift initializer and optional chain
2022-07-25 08:34:00 【Fluttering moth】

The initializer
required
use required Decorate the specified initializer , Indicates that all its subclasses must implement this initializer ( Through inheritance or rewriting )
If a subclass overrides required The initializer , You have to add required, Don't add override
class Person {
required init() {}
init(age: Int) {}
}
class Student: Person {
init(no: Int) {
super.init(age: 0)
}
required init() {
super.init()
}
}
Attribute viewer
- Assigning a property of a parent class to its own initializer does not trigger the property observer , But assigning a value in the initializer of a subclass will trigger the property observer
class Person {
var age: Int {
willSet {
print("willSet", newValue)
}
didSet {
print("didSet", oldValue, age)
}
}
init() {
self.age = 0
}
}
class Student: Person {
override init() {
super.init()
self.age = 1
}
}
Failed initializer
- class 、 Structure 、 Enumeration can be used init? Define a failable initializer
class Person {
var name: String
init?(name: String) {
if name.isEmpty {
return nil
}
self.name = name
}
}
It is not allowed to define parameter labels at the same time 、 Number of parameters 、 Failed initializers and non failed initializers with the same parameter types
It can be used init! Define a failable initializer for implicit unpacking
Failed initializers can call non failed initializers , The non failable initializer calls the failable initializer and needs to unpack
class Person {
var name: String
init?(name: String) {
if name.isEmpty {
return nil
}
self.name = name
}
convenience init() {
self.init(name: "")!
}
}
If the initializer calls a failable initializer, the initialization fails , Then the whole initialization process fails , And then the code stops executing
You can rewrite a failable initializer with a non failable initializer , But the reverse is not possible .
De initializer (deinit)
- deinit It is called de initializer , Be similar to C++ Destructor of 、OC Medium dealloc Method
When the instance object of the class is released from memory , Will call the instance object deinit Method
class Person {
deinit {
print("Person The object is destroyed ")
}
}
deinit No parameters are accepted , You can't write parentheses , Cannot call by itself
Of the parent class deinit Can be inherited by subclass
A subclass deinit The parent class will be called after the implementation is completed deinit
Optional chain (Optional Chaining)
class Car {
var price = 0
}
class Dog {
var weight = 0
}
class Person {
var name: String = ""
var dog: Dog = Dog()
var car: Car? = Car()
func age() -> Int {
18
}
func eat() {
print("Person eat")
}
subscript(index: Int) -> Int {
return index
}
}
var person: Person? = Person()
var age = person?.age()//Int? Optional(18)
var age1 = person!.age() // Int
var name = person?.name //String?
var index = person?[6] // Int?
If the option is nil, Calling method 、 Subscript 、 Property failed , The result is nil
If the option is not nil, Calling method 、 Subscript 、 Attribute succeeded , The results will be packaged as options
If the result is optional , No repacking
Judge whether the method has been called successfully :
if let age = person?.age() { // ()?
print(" call age success ", age)
} else {
print(" call age Failure ")
}
Form optional chain :
- Multiple ? Can be linked together
If any node in the chain is nil, Then the whole chain will fail to call , There are many applications of optional chain , stay OC We usually add a lot of judgment to avoid collapse , stay Swift Inside , Because having an optional chain will reduce a lot of our own judgment , Improved security .
var dog = person?.dog // Dog?
var weight = person?.dog.weight // Int?
var price = person?.car?.price // Int?
var scores = [
"Jack" : [86, 82, 84],
"Rose" : [79, 94, 81]
]
scores["Jack"]?[0] = 100
scores["Rose"]?[2] += 10
scores["Kate"]?[0] = 88
var num1: Int? = 5
num1? = 10 // Optional(10)
var num2: Int? = nil
num2? = 10 // nil
var dict: [String : (Int, Int) -> Int] = [
"sum" : (+), // Two Int Type addition , Return to one Int type
"difference" : (-)
]
var result = dict["sum"]?(10, 20) // Optional(30), Int?
边栏推荐
- 2022-07-19 Daily: too many icml2022 papers to read? "One sentence comments on 1234 paper highlights" helps you quickly lock
- 刷题《剑指Offer》day01
- Talk about your transformation test development process
- Memcached data cache database (improve efficiency)
- Huawei device remote login (Telnet, SSH) configuration
- Sun Tzu's art of war
- Summary of SQL skills in data warehouse development
- [dark horse programmer] redis learning notes 004: master-slave replication + sentinel mode + cluster
- Raspberrypico serial communication
- 016 fundamentals of machine learning mathematics: Introduction
猜你喜欢

A powerful port scanning tool (nmap)

Chapter 3 business function development (realize the real-time response of the select all button)

Online bookstore system based on jsp+servlet+mysql
![[Sesame Street family] & Bert Bart Roberta](/img/ff/c685065cd413bd4cffd996fd9afeaa.png)
[Sesame Street family] & Bert Bart Roberta

Chapter 3 business function development (modifying clues, data echo and modifying data)
![[ten thousand words long text] Based on LSM tree thought Net 6.0 C # realize kV database (case version)](/img/07/235785b7658b5ae022dfa3f53ec86d.png)
[ten thousand words long text] Based on LSM tree thought Net 6.0 C # realize kV database (case version)

Idea failed to start the project yamlexception Chinese file encoding format

Advanced C language (11) - user defined data types

Mongodb database

TCGA simple download tool V16 installation error
随机推荐
CM4 development cross compilation tool chain production
Node+js build time server
Redis fragment cluster
Idea reads configuration files such as validationmessages.properties Chinese garbled
C # introductory series (30) -- exception handling
Nuscenes dataset 3D mot demo, end-to-end target detection and tracking, joint detection and tracking framework
Keep your Eyes on the Lane: Real-time Attention-guided Lane Detection
How to set up a personal website for free
华为设备远程登录(Telnet、SSH)配置
serialization and deserialization
Raspberrypico serial communication
技术面②Mysql中的索引(index)类型有哪些并简要介绍一下?什么时候需要创建索引?什么时候不需要创建索引?为什么创建索引后查询速度会提高?
Redis分片集群
Summary of SQL skills in data warehouse development
Efcore's solution of multi tenant zero script, table and database read-write separation under SaaS system
016 fundamentals of machine learning mathematics: Introduction
Rstudio shows that it can't connect to the web page, or it has a new website.
C#入门系列(三十) -- 异常处理
Rk3399 development board i2c4 attaching EEPROM instance
孙子兵法随感