当前位置:网站首页>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?
边栏推荐
- TCGA simple download tool V16 installation error
- 【5G NR】3GPP常用协议整理
- C#入门系列(三十) -- 异常处理
- 第3章业务功能开发(查询线索)
- [dark horse programmer] redis learning notes 005: enterprise level solutions
- QA robot sequencing model
- Chapter 3 business function development (modifying clues, data echo and modifying data)
- 一次简单的SQL注入靶场练习
- Force buckle - 1046. Weight of the last stone
- Summary of SQL skills in data warehouse development
猜你喜欢

Eureka forced offline service

Raspberry connects EC20 for PPP dialing

第3章业务功能开发(查询线索)

A simple SQL injection shooting range exercise

Network packet loss, network delay? This artifact helps you solve all problems

【黑马程序员】Redis学习笔记005:企业级解决方案

Online shopping E-commerce mall system based on jsp+servlet+mysql+

Initial knowledge of WebService (generate jar packages and call methods in remote services)

Centernet network structure construction

@Autowired注解的实现原理
随机推荐
[dark horse programmer] redis learning notes 003: redis transactions
Chapter 3 business function development (modifying clues, data echo and modifying data)
nuscenes数据集3D MOT demo,端到端的目标检测和跟踪,检测跟踪联合框架
Redis fragment cluster
My creation anniversary
A simple SQL injection shooting range exercise
Chapter 3 business function development (query clues)
When easyexcel uses converter conversion to inject nullpoint exception
@Autowired注解的原理
Advanced C language (11) - user defined data types
RK3399开发板I2C4挂载EEPROM实例
C#入门系列(三十) -- 异常处理
[dark horse programmer] redis learning notes 005: enterprise level solutions
How to set up a personal website for free
RTOS series (13): assembly LDR instruction, LDR pseudo instruction, [rn] register indirect reference detailed analysis
Test the mock data method of knowing and knowing
【5G NR】UE注册拒绝原因
Surpassing transformer, Tsinghua, byte significantly refresh parallel text generation SOTA performance | ICML 2022
Hotel room management system based on jsp+servlet+mysql
Foundation 32: page element positioning method XPath --- axis positioning method