@LarryTwofly
2023-03-30T02:39:38.000000Z
字数 7498
阅读 236
iOS
1、版本记录
2014年8月:1.0版本、1.1版本、1.2版本
2015年9月:2.0版本、2.1版本
2016年3月:2.2版本、2.3版本
2016年9月:3.0版本、3.1版本
2017年9月:4.0版本
目前:4.2版本
2、swift优势
(1)性能:
![image_1cmno9ap31r9o15jk1pc8g221ps1u.png-71.5kB][1]
(2)开源
3、链接:
https://swift.org/about/
https://developer.apple.com/swift/
let 来声明常量,var来声明变量
let maximumNumberOfLoginAttempts = 4var currentLoginAttempt = 0
可以一行声明多个
var x = 0.0, y = 0.0, z = 0.0
变量welcomeMessage为String类型
var welcomeMessage: String
let π = 3.14159let 你好 = "你好世界"let 🐮 = "dogcow"let 🐶 = "dogcow"
原则:字母数字下划线,数字不能开头;大部分Unicode编码
禁止:数学符号,箭头,保留的(或者非法的)Unicode 码位,连线与制表符。
let π = 3.14159let 你好 = "你好,亲爱的"let 🐂 = "大牛"let 🐶 = "狗狗"print(π) //3.14159print(你好) //你好,亲爱的print("say:\(你好)") //say:你好,亲爱的print("say:"+你好) //say:你好,亲爱的print("say:",你好) //say:%@ 你好,亲爱的print(🐂+"say:"+你好+🐶) //大牛say:你好,亲爱的狗狗
(1)// 这是一个注释(2)/* 这是一个, 多行注释 */(3)/* 这是第一个多行注释的开头/* 这是第二个被嵌套的多行注释 */这是第一个多行注释的结尾 */
看上面,仔细看看
Swift 提供了8,16,32和64位的有符号和无符号整数类型(Int8、Int16、Int32和Int64)
(1)Int类型
在32位平台上,Int 和 Int32 长度相同。
在64位平台上,Int 和 Int64 长度相同。
(2)UInt类型
在32位平台上,UInt 和 UInt32 长度相同。
在64位平台上,UInt 和 UInt64 长度相同。
(3)其他:整数范围、整数符号
分两种
(1)、Double表示64位浮点数。当你需要存储很大或者很高精度的浮点数时请使用此类型。
(2)、Float表示32位浮点数。精度要求不高的话可以使用此类型。
(1)、类型推断
// meaningOfLife 会被推测为 Int 类型let meaningOfLife = 42// pi 会被推测为 Double 类型let pi = 3.14159// anotherPi 会被推测为 Double 类型let anotherPi = 3 + 0.14159
(2)、类型安全
var meaningOfLife = 42// meaningOfLife 会被推测为 Int 类型meaningOfLife = "我是字符串" //报错啦
说明: Swift 是类型安全的,所以它会在编译你的代码时进行类型检查(type checks),并把不匹配的类型标记为错误。这可以让你在开发的时候尽早发现并修复错误。
规则:
- 一个十进制数,没有前缀。
- 一个二进制数,前缀是0b。
- 一个八进制数,前缀是0o。
- 一个十六进制数,前缀是0x。
(1)十进制为17的不同进制
let decimalInteger = 17let binaryInteger = 0b10001 // 二进制的17let octalInteger = 0o21 // 八进制的17let hexadecimalInteger = 0x11 // 十六进制的17
(2)指数表示:exp
- 十进制:1.25e2 表示 1.25 × 10^2,等于 125.0。
- 十六进制:0xFp2 表示 15 × 2^2,等于 60.0。
(3)可读性
let paddedDouble = 000123.456let oneMillion = 1_000_000let justOverOneMillion = 1_000_000.000_000_1
let three = 3let pointOneFourOneFiveNine = 0.14159let pi = Double(three) + pointOneFourOneFiveNine// pi 等于 3.14159,所以被推测为 Double 类型
typealias AudioSample = UInt16
let orangesAreOrange = truelet turnipsAreDelicious = false
let http404Error = (404, "Not Found")// http404Error 的类型是 (Int, String),值是 (404, "Not Found")
var surveyAnswer: String?// surveyAnswer 被自动设置为 nil
函数
//函数实现func canThrowAnError() throws {// 这个函数有可能抛出错误}//调用函数do {try canThrowAnError()// 没有错误消息抛出} catch {// 有一个错误消息抛出}
let age = -3assert(age >= 0, "A person's age cannot be less than zero")// 因为 age < 0,所以断言会触发assert(age >= 0)//等价于:没有断言信息
(1)count、索引index、插入insert、删除remove、子字符串prefix
说明:运算符分为一元、二元和三元运算符
- 一元运算符对单一操作对象操作(如 -a)。一元运算符分前置运算符和后置运算符,前置运算符需紧跟在操作对象之前(如 !b),后置运算符需紧跟在操作对象之后(如 c!)。
- 二元运算符操作两个操作对象(如 2 + 3),是中置的,因为它们出现在两个操作对象之间。
- 三元运算符操作三个操作对象,和 C 语言一样,Swift 只有一个三元运算符,就是三目运算符(a ? b : c)。
运算符分类
- 赋值运算符
- 算术运算符
- 求余运算符
- 一元负号运算符
- 一元正号运算符
- 组合赋值运算符
- 比较运算符(Comparison Operators)
- 三目运算符(Ternary Conditional Operator)
- 空合运算符(Nil Coalescing Operator)
let defaultColorName = "red"var userDefinedColorName: String? //默认值为 nil// userDefinedColorName 的值为空,所以 colorNameToUse 的值为 "red"var colorNameToUse = userDefinedColorName ?? defaultColorName
- 区间运算符(Range Operators)
(1)闭区间运算符
for index in 1...5 {print("\(index) * 5 = \(index * 5)")}// 1 * 5 = 5// 2 * 5 = 10// 3 * 5 = 15// 4 * 5 = 20// 5 * 5 = 25
(2)半开区间运算符
let names = ["Anna", "Alex", "Brian", "Jack"]for i in 0..<names.count-1 {print("第 \(i + 1) 个人叫 \(names[i])")}/*输出:第 1 个人叫 Anna第 2 个人叫 Alex第 3 个人叫 Brian*/
(3)单侧区间运算符
let names = ["Anna", "Alex", "Brian", "Jack"]for i in 0..<names[2..] {print(name)}/*输出BrianJack*/for i in 0..<names[...2] {print(name)}/*输出AnnaAlexBrian*///单侧半开区间for name in names[..<2] {print(name)}/*输出AnnaAlex*/
- 逻辑运算符(Logical Operators)
(1)逻辑非(!a)
(2)逻辑与(a && b)
(3)逻辑或(a || b)
var someInts = [Int]()//添加元素someInts.append(3)//插入元素a.insert(9, at: 0)
// anotherThreeDoubles 被推断为 [Double],等价于 [2.5, 2.5, 2.5]var anotherThreeDoubles = Array(repeating: 2.5, count: 3)// sixDoubles 被推断为 [Double],等价于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]var sixDoubles = threeDoubles + anotherThreeDoubles
if shoppingList.isEmpty {print("The shopping list is empty.")} else {print("The shopping list is not empty.")}
(1)
for item in shoppingList {print(item)}
(2)
for (index, value) in shoppingList. enumerated() {print("Item \(String(index + 1)): \(value)")}
表示:Set
表示:[key 1: value 1, key 2: value 2, key 3: value 3]
//元素遍历let names = ["Anna", "Alex", "Brian", "Jack"]for name in names {print("Hello, \(name)!")}// Hello, Anna!// Hello, Alex!// Hello, Brian!// Hello, Jack!
//根据键值对let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]for (animalName, legCount) in numberOfLegs {print("\(animalName)s have \(legCount) legs")}
//根据下标遍历for index in 1...5 {print("\(index) times 5 is \(index * 5)")}
//省略元素。原来:for p in names 简化后:for _ in nameslet base = 3let power = 10var answer = 1for _ in 1...power {answer *= base}
//阶梯式遍历let minuteInterval = 5for tickMark in stride(from: 0, to: minutes, by: minuteInterval){// 每5分钟渲染一个刻度线 (0, 5, 10, 15 ... 45, 50, 55)}
which stement {case 1:...case 2:...default:...}
which stement {case 1,3,5,7,8:...case 2:...default:...}
which stement {case let index where index <= 100:...case 101:...default:...}
which stement {case 0...100:...case 101..200:...default:...}
let somePoint = (1, 1)switch somePoint {case (0, 0):print("\(somePoint) is at the origin")case (_, 0):print("\(somePoint) is on the x-axis")case (0, _):print("\(somePoint) is on the y-axis")case (-2...2, -2...2):print("\(somePoint) is inside the box")default:print("\(somePoint) is outside of the box")}
let anotherPoint = (2, 0)switch anotherPoint {case (let x, 0):print("on the x-axis with an x value of \(x)")case (0, let y):print("on the y-axis with a y value of \(y)")case let (x, y):print("somewhere else at (\(x), \(y))")}
while condition {statements}
repeat {statements} while condition
说明:控制转移语句改变你代码的执行顺序,通过它可以实现代码的跳转。Swift 有五种控制转移语句:
- continue
- break
- fallthrough(贯穿)
- return
- throw
which stement {case let index where index <= 100:...fallthroughcase 50...200:...default:...}
func greet(person: [String: String]) {guard let name = person["name"] else {return}print("Hello \(name)")}
表示:label name: while condition { statements }
let finalSquare = 6var square = 0gameLoop: while square != finalSquare {square = arc4random() % 6 + 1...}print("Game over!")
func sayHelloWorld() {print(str)}func sayHelloWorld(str: String) {print(str)}func sayHelloWorld2(str: String?) {print(str)}func sayHelloWorld3(str: String = "default str") {print(str)}func sayHelloWorld3(_ str: String = "default str") {print(str)}func sayHelloWorld3(str: String...) {print(str)}
func sayHelloWorld() -> String {return "hello world"}func sayHelloWorld() -> (String, String) {return ("xiaoming", "hello world")}
func sayHelloWorld3(str: String = "default str") {print(str)}
let s = ["ab","ccc","ad","dsa","banadsf"]let ss = s.sorted(by: backward)let sss = s.sorted { (s1, s2) -> Bool inreturn s1 > s2}let ssss = s.sorted(by: { $0 > $1 })let sssss = s.sorted(by: > )func backward(_ s1: String, _ s2: String) -> Bool {return s1 > s2}
(1)map函数
let values = [2, 4, 5, 7]//获取://for循环实现var squares: [Double] = []for value in values {squares.append(value*value)}//map实现let squares = values.map { $0 * $0 }//map原型一let squares = values.map { value in value * value}//map原型二let squares = values.map( { (value: Double) -> Double inreturn value * value})//map原型三let squares = values.map(backward)func backward(_ s1: Int , _ s2: Int) -> Int {return s1 * s2}
(2)filter函数
let digits = [1, 4, 10, 15]let even = digits.filter { $0 % 2 == 0 }举例子:paperSlices.removeAll()var temps = papers.dropFirst(0)while let first = temps.first {let s = temps.prefix { first.createdAt.isSameDay($0.createdAt) }paperSlices.append(Array(s))temps = temps.dropFirst(s.count)}
(3)Reduce组合函数
// 以下两行输出:28.0let items = [2.0, 4.0, 5.0, 7.0]let total = items.reduce(10, combine: +)// 以下两行输出:"abcdefghi"let codes = ["abc", "def", "ghi"]let text = codes.reduce("", combine: +)//Reduce函数原型:let name = ["alan", "brian", "charlie"]let scv = name.reduce("==") {text, name in "\(text), \(name)"}// "==, alan, brian, charlie"
(4)FlatMap函数
// 以下两行输出:[5, 2, 7, 4, 8, 9, 1, 3]let collections = [[5, 2, 7], [4, 8], [9, 1, 3]]let flat = collections.flatMap { $0 }