swift
Day 1
变量
let 常量
swift 使用 let 作为 常量
var 变量
swift 使用 var 作为变量
变量类型
在 swift ,一旦变量类型被固定了,就不允许改变,比如:
var name = "chenbobo"
name = 23 // 这是不允许的 字符串
字符串插值语法:
let name = "chenbobo"
let age = 23
let message = "Hello, my name is \(name) and I'm \(age) years old."
print(message) // Hello, my name is chenbobo and I'm 23 years old.数组
swift 不允许不同类型的数组在一起,这点和其他强类型语言一样:
var scores = Array<Int>() // 创建一个 int 类型数组
scores.append(100)
scores.append(80)
scores.append(30)
print(scores)
var names = Array<String>()
names.append("zhangsan")
names.append("lisi")
names.append("wangwu")
print(names.count)
names.remove(at: 2)
print(names)
names.removeAll()
print(names)
names.insert("chenbobo", at: 0)
print(names)
// 有多重方式定义指定类型数组
var soda: [String] = ["Coke"]
var teams: [String] = [String]()
var cities: [String] = []let citys = ["beijing", "shanghai", "siping", "gongzhuling"]
// 排序
print(citys.sorted())
// 数组翻转
let reversedCitys = citys.reversed()
print(reversedCitys)
// 输出为:输出
["beijing", "gongzhuling", "shanghai", "siping"]
ReversedCollection<Array<String>>(_base: ["beijing", "shanghai", "siping", "gongzhuling"])
字典
写法:
let person = [
"name":"chenshibo",
"age": "23",
"address": "beijing"
]
// 必须指定 default,否则会出错
print(person["name", default: "Unknown"])
如果想要指定 字典 key value 类型:
var height = [String: Int]()
height["Yao Ming"] = 229
height["LeBron James"] = 206
print(height)
枚举
// 枚举
enum Weekday {
case monday
case tuesday
case wednesday
case thursday
case firday
}
var day = Weekday.monday
day = Weekday.firday
print(day)
// 如果在上边已经赋值过,则这里可以直接写 . 的写法,这样更加高效
day = .thursday
print(day)
enum UIStyle {
case light, dark, system
}类型
let playerName: String = "Roy"
let luckyNumber: Int = 12
let pi: Double = 3.1415926
var isAuthenticated: Bool = true
var albums: [String] = ["Red", "Fearless"]
var user: [String: String] = ["id": "@chenbobo"]
var books: Set<String> = Set([
"The Bluest Eye",
"Foundation",
"Girl, Woman, Other"
])
随机数
对于 Int 和 Double 有方法可以创建范围内的随机数
// 创建一个介于 1 和 1000 之间的新整数
let id = Int.random(in: 1...1000)
// 生成一个介于 0 和 1 之间的随机小数
let amount = Double.random(in: 0...1)
函数
定义函数:
func showWelcome() {
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")
}
func showMessage(message: String) {
print("You input message is \(message)")
}
// 调用函数时,必须指定形参
showMessage(message: "hello")
带返回值的函数:
对于有返回值的函数,必须指定返回值类型
func aAddB(a: Int, b: Int) -> Int {
return a + b
}
let result = aAddB(a: 10, b: 5)
print(result)如果代码中只有一行,并且指定了返回值类型,那么 swift 会知道这一行必须返回,所以可以省略 return
func aAddB(a: Int, b: Int) -> Int {
a + b
}
let result = aAddB(a: 10, b: 5)
print(result)返回多个值:
// 这种返回类型为元组,可以直接使用 返回.元素 的方式来取值
func getName (firstName: String, lastName: String) -> (firstName: String, lastName: String) {
(firstName, lastName)
}
let userData = getName(firstName: "chen", lastName: "bobo")
print("The user is \(userData.firstName) \(userData.lastName)")
// 当然也可以直接使用 () 进行取值
let (firstName, lastName) = getName(firstName: "Alvin", lastName: "key")
print("The last user is \(firstName) \(lastName)")
// 如果不需要某个值
let (firstName, _) = getName(firstName: "Alvin", lastName: "key")
print("The last user is \(firstName) ")swift 支持多个函数使用同一命名,然后通过传入不同的参数名称来区分不同的函数
func showName (chineseName: String) {
print("showName chinese name id \(chineseName)")
}
func showName (englishName: String) {
print("showName english name id \(englishName)")
}
showName(chineseName: "陈博博")
showName(englishName: "chenbobo")如果不想在调用函数的时候传值,可以使用下划线移除外部参数标签,如:
func isUppercase(_ string: String) -> Bool {
string == string.uppercased()
}
let string = "HELLO, WORLD"
let result = isUppercase(string)外部函数传递命名参数,内部函数修改形参名,可以实现
func printTimesTables(for number: Int) {
for i in 1...12 {
print("\(i) x \(number) is \(i * number)")
}
}
printTimesTables(for: 5)函数默认值:
func findDirections(from: String, to: String, route: String = "fastest", avoidHighways: Bool = false) {
// code here
}异常处理
在 Swift 中,异常处理使用三个字段: do try catch ,这三个字段来处理异常
do {
try throwingFunction1() // 这里会检查函数内部是否有错误,并抛出异常
nonThrowingFunction1() // 这里就算发生了错误,也不会抛出异常,所以不会被 cache 捕获
try throwingFunction2()
nonThrowingFunction2()
try throwingFunction3()
} catch {
// handle errors
}
Day 2
闭包
和 js 的闭包类似,都是:内部函数引用了外部变量,并且这个外部变量不会随着外层函数结束而销毁
基本闭包,相当于一个匿名函数:
let driving = {
print("I'm driving in my car")
}
driving()接收参数的闭包:
let driving = { (place: String) in
print("I'm going to \(place) in my car")
}
// 这里可以不用指定参数
driving("BeiJing")返回值的闭包
let sumResult = { (a: Int, b: Int) -> Int in
return a + b
}
let sumResultData = sumResult(10, 20)
print("The sum is \(sumResultData)")
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Alvin
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果