Swift编程

Swift语法 Swift5 【05 - 可选项】

2020-05-08  本文已影响0人  Liwx

iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

00 - 汇编
01 - 基础语法
02 - 流程控制
03 - 函数
04 - 枚举
05 - 可选项
06 - 结构体和类
07 - 闭包
08 - 属性
09 - 方法
10 - 下标
11 - 继承


01-可选项(Optional)

var name: String? = "Jack"
name = nil

var age: Int?   // 默认就是nil
age = 10  // Optional(10)
age = nil
var array = [1, 15, 40, 29]
func get(_ index: Int) -> Int? {
    if index < 0 || index >= array.count {
        return nil
    }
    return array[index]
}
print(get(1))   // Optional(15)
print(get(-1))  // nil
print(get(4))   // nil

02-强制解包


var age: Int?   // 默认就是nil
age = 10
age = nil
QQ20200420-154654.png
var age: Int? = 10

// 可选项不能直接参与运算
//var num = age + 10  // error: value of optional type 'Int?' must be unwrapped to a value of type 'Int'
var num = age! + 20

print(age)      // Optional(10)
print(num)      // 30

var age: Int?
print(age!)     // 报错: Fatal error: Unexpectedly found nil while unwrapping an Optional value

03-判断可选项是否包含值

let number = Int("123")
if number != nil {
    print("字符串转换整数成功: \(number!)")  // number!: 强制解包
} else {
    print("字符串转换整数失败")
}
// 字符串转换整数成功: 123

04-可选项绑定(Optional Binding)

if let number = Int("123") {
     print("字符串转换整数成功: \(number)")  // number无需再解包
    // number是强制解包之后的Int值
    // number作用于仅限于这个大括号
} else {
    print("字符串转换整数失败")
}

enum Season : Int {
    case spring = 1, summer, autumn, winter
}

if let season = Season(rawValue: 6) {
    switch season {
    case .spring:
        print("the season is spring")
    default:
        print("the season is other")
    }
} else {
    print("no such season")
}
// no such season

05-等价写法

// 写法1
if let first = Int("4") {
    if let second = Int("42") {
        if first < second && second < 100 {
            print("\(first) < \(second) < 100")
        }
    }
}
// 4 < 42 < 100

// - 可选项绑定,多个条件要同时成立,用`逗号`隔开
// 写法2 推荐
if let first = Int("4"),
    let second = Int("42"),
    first < second && second < 100 {
    print("\(first) < \(second) < 100")
}
// 4 < 42 < 100

注意: 不允许 可选项绑定&&一起使用

if let s = Season(rawValue: 2) && age > 10 {

}

06-while循环中使用可选项绑定

var strs = ["10", "20", "abc", "-20", "30"]
var index = 0
var sum = 0
while let num = Int(strs[index]), num > 0 {
    sum += num
    index += 1
}
print(sum)  // 30

07-空合并运算符??(Nil-Coalescing Operator)

// ??后面参数类型为T?, 则返回值类型为T?
public func ?? <T>(optional: T?, defaultValue: @autoclosure
() throws -> T?) rethrows -> T?

// ??后面参数类型为T, 则返回值类型为T
public func ?? <T>(optional: T?, defaultValue: @autoclosure
() throws -> T) rethrows -> T


let a: Int? = 1
let b: Int? = 2
let c = a ?? b  // c是Int?, Optional(1)
print(c)  // Optional(1)
let a: Int? = nil
let b: Int? = 2
let c = a ?? b  // c是Int?, Optional(2)
print(c)  // Optional(2)
let a: Int? = nil
let b: Int? = nil
let c = a ?? b  // c是Int?, nil
print(c)  // nil
let a: Int? = 1
let b: Int = 2
let c = a ?? b  // c是Int, 1
print(c)  // 1
let a: Int? = nil
let b: Int = 2
let c = a ?? b  // c是Int, 2
print(c)

let a: Int? = nil
let b: Int = 2
// 如果不使用??运算符
let c: Int
if let tmp = a {
    c = tmp
} else {
    c = b
}

08-多个?? 一起使用

let a: Int? = 1
let b: Int? = 2
let c = a ?? b ?? 3 // c是Int, 1  
print(c)
let a: Int? = nil
let b: Int? = 2
let c = a ?? b ?? 3
print(c)  // c是Int, 2
let a: Int? = nil
let b: Int? = nil
let c = a ?? b ?? 3 // c是Int, 3
print(c)

09-??跟if let配合使用

let a: Int? = nil
let b: Int? = 2
// 类似于if a != nil || b != nil
if let c = a ?? b {
    print(c)    // 2
}
let a: Int? = 1
let b: Int? = 2
// 类似于if a != nil && b != nil
if let c = a, let d = b {
    print("c:", c, "d:", d)  // c: 1 d: 2
}

10-if-let语句实现登陆

func login(_ info: [String : String]) {
    
    let userName: String
    if let tmp = info["userName"] {
        userName = tmp
    } else {
        print("请输入用户名")
        return
    }
    
    let password: String
    if let tmp = info["password"] {
        password = tmp
    } else {
        print("请输入密码")
        return
    }
    
    // if userName ....
    // if password ....
    print("用户名: \(userName)", "密码: \(password)")
}
login(["userName": "liwx", "password": "123456"])   // 用户名: liwx 密码: 123456
login(["password": "123456"])   // 请输入用户名
login(["userName": "liwx"])     // 请输入密码

11-guard语句


guard 条件 else {
    // do something ...
    退出当前作用域
    // return、break、continue、throw error
}

func login(_ info: [String : String]) {
    
    // 使用guard语句进行可选项绑定
    // userName和password 可以在外层作用域中使用
    guard let userName = info["userName"] else {
        print("请输入用户名")
        return
    }
    guard let password = info["password"] else {
        print("请输入密码")
        return
    }
    
    // if userName ....
    // if password ....
    print("用户名: \(userName)", "密码: \(password)")
}
login(["userName": "liwx", "password": "123456"])

12-隐式解包(Implicitly Unwrapped Optional)


let num1: Int! = 10
let num2: Int = num1
if num1 != nil {
    // 隐式解包可选项的值可以直接运算
    print(num1 + 6) // 16
}

if let num3 = num1 {
    print(num3)     // 10
}
// Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
//let num4: Int! = nil
//let num5: Int = num4

13-字符串插值

var age: Int? = 10
print("My age is \(age)")

// 至少有3种方法消除警告
print("My age is \(age!)")
print("My age is \(String(describing: age))")
print("My age is \(age ?? 0)")

14-多重可选项


var num1: Int? = 10
var num2: Int?? = num1
var num3: Int?? = 10
print(num2 == num3) // true 断点观察
(lldb) fr v -R num1
(Swift.Optional<Swift.Int>) num1 = some {
  some = {
    _value = 10
  }
}
(lldb) fr v -R num2
(Swift.Optional<Swift.Optional<Swift.Int>>) num2 = some {
  some = some {
    some = {
      _value = 10
    }
  }
}
(lldb) fr v -R num3
(Swift.Optional<Swift.Optional<Swift.Int>>) num3 = some {
  some = some {
    some = {
      _value = 10
    }
  }
}
image.png
var num1: Int? = nil
var num2: Int?? = num1
var num3: Int?? = nil
print(num2 == num3) // false
print(num1 == num3) // false
(lldb) fr v -R num1
(Swift.Optional<Swift.Int>) num1 = none {
  some = {
    _value = 0
  }
}
(lldb) fr v -R num2
(Swift.Optional<Swift.Optional<Swift.Int>>) num2 = some {
  some = none {
    some = {
      _value = 0
    }
  }
}
(lldb) fr v -R num3
(Swift.Optional<Swift.Optional<Swift.Int>>) num3 = none {
  some = some {
    some = {
      _value = 0
    }
  }
}
image.png

iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

下一篇: 06 - 结构体和类
上一篇: 04 - 枚举


上一篇下一篇

猜你喜欢

热点阅读