美文网首页
Swift 5.1 极简参考手册

Swift 5.1 极简参考手册

作者: baihualinxin | 来源:发表于2019-12-04 11:17 被阅读0次

声明常量和变量
• 使用 let 关键字声明一个常量

let double: Double = 2.0
double = 3.0 // 错误:不能给常量重新赋值
let inferredDouble = 2.0 // 推断为一个 Double 类型

• 使用 var 关键字声明一个变量

var mutableInt: Int = 1
mutableInt = 2 // OK: 可以给一个变量重新赋值

• 数值类型转换

let integerValue = 8
let doubleValue = 8.0
//let sum = integerValue + doubleValue // 错误:类型不匹配

• 使用显式的方法来防止隐藏的转换错误并有助于明确类型转换意图

let sum = Double(integerValue) + doubleValue // OK: 两个值有相同类型

字符串
• 使用字符串字面量来初始化一个常量或变量

let helloWorld = "Hello, World!"

• 使用多行字符串字面量来跨越多行

let helloWorldProgram = """
A "Hello, World!" program generally is a computer program
that outputs or displays the message "Hello, World!"
"""

• 空字符串

let emptyString = "" // 使用字符串字面量
let anotherEmptyString = String() // 初始化语法

• 修改字符串

var mutableString = "Swift"
mutableString += " is awesome!"

• 字符串插值

print("The value is \(doubleValue)") // 插入一个 Double 值
print("This is my opinion: \(mutableString)") // 插入一个字符串

元组
• 将多个值组合为一个复合值

let httpError = (503, "Server Error")

• 分解元组的内容

let (code, reason) = httpError

// 另一种分解方式
let codeByIndex = httpError.0
let reasonByIndex = httpError.1

• 使用 _ 来忽略元组的某些部分

let (_, justTheReason) = httpError

可选项
• catchphrease 可以包含 String 或 nil

var catchphrease: String? // 由编译器自动设置为nil
catchphrease = "Hey, what's up, everybody?"

• 强制解包操作符 (!)

// 如果 catchphrease 不是nil,count1 包含 
catchphrease 的计数值;
// 否则程序崩溃
let count1: Int = catchphrease!.count
 var catchphrease:String! //强制指定类型解包
catchphrease="hey,what's up,everybody?"
let count1:Int=catchphrease.count //就不需要解包符

• 可选绑定

// 如果 catchphrease?.count 返回的可选 Int 包含一个值,
// 则将一个称为 count 的新常量设置为可选中包含的值
if let count = catchphrease?.count {
  print(count)
}

• 合并操作符(??)

// 如果 catchphrease 不是 nil,count2 包含 
catchphrease 的 count 值;否则为 0
let count2: Int = catchphrease?.count ?? 0

• 链式操作符(?)

// 如果 catchphrease 不是nil,count3 包含 
catchphrease 的 count 值;否则为 nil
let count3: Int? = catchphrease?.count

相关文章

网友评论

      本文标题:Swift 5.1 极简参考手册

      本文链接:https://www.haomeiwen.com/subject/kcwkgctx.html