前言
swift 基础知识合集
参考:Swift编程
let a = 10 //声明常亮
var b = 0 //声明变量
//1.1常量和变量的命名
let π = 3.14159
let 你好 = "你好世界"
let = "dogcow"
var str: String
str = "Hello"
//2.1定义多个同类型变量
var red, green, blue: Double
//3.1 整数
//查看对应类型最大值和最小值
let minValue = UInt8.min // minValue 为 0,是 UInt8 类型
let maxValue = UInt8.max // maxValue 为 255,是 UInt8 类型
//int 范围 -2,147,483,648 ~ 2,147,483,647
//3.2 浮点数 3.14159、0.1 和 -273.15
// 两种类型都匹配的情况下,将优先选择 Double。
//3.3 Bool 布尔
var bool = true
//3.4 String 字符串
var hello = "Hello, World!"
//3.5 Character 字符
var Character = "C"
//3.6 类型安全和类型推断
let length = 42 // 会被推测为 Int 类型
let pi = 3.14159 // 会被推测为 Double 类型
let anotherPi = 3 + 0.14159 // 会被推测为 Double 类型
//4.1 整数->浮点
let three = 3
let p = Double(three) + 0.1415926
//4.2 浮点 -> 整数
let integerPi = Int(p)
//typealias newname = type
typealias Feet = Int
var distance: Feet = 100
var a = (1,25.5,"hello",true)
var b: (Int,String) = (1,"hello")
//取值方法 类数组[] 索引
print(a.0)//取a元组中的第一个元素
//赋值方法
a.0 = 10
//带参数的元组
var a = (name1: 10,name2: "nihao")
a.name1//取值
//元组拆分
let (name1,name2) = (10,"你好")
print(name1) //10
print(name2) //你好
var a: Int? = 10 //打印会出现optional
var b: Int? // 默认为nil
// !强制解包
print(a!)
if let d = Int("123") {
print("d赋值成功:\(d)")
} else {
print("赋值失败")
}
if let one = Int("4"), let two = Int("42"), one < two && two < 100 {
print("\(one) < \(two) < 100")
}
//输出 4 < 42 < 100
func makeSomething() throws {
// 这个函数有可能抛出错误
}
do {
try makeSomething()
print("do something成功")
} catch{
print("do something失败")
}
+ - * / //基础运算符:加减乘除
== != > < >= <= //比较运算符
&& || ! //逻辑运算符 与或非
a ? b : c //三元运算符: 如果a为真取b的值 为假取c的值
?? //合并空值运算符 (没有则取一个默认值a ?? b)
(a...b) //区间运算符
(a..<b) //半开区间运算符
[2...] //闭区间的 单侧区间
[..<2] //半开区间操作符的单侧表达形式
let str1 = "These are the same."
let str2 = """
These are the same.
"""
var str = ""
// 检查是否为空
if str.isEmpty {
print("str是空字符串")
}
// 拼接字符串
let str1 = "hello"
let str2 = " world"
var str3 = str1 + str2
// 遍历字符串
for char in "character" {
print(char)
var str = "hello";
//尾部添加
str.append(" world")
// str = helloworld
//插值
str.insert("!", at: str.endIndex)
// str = hello world!
//移除
str.remove(at: str.index(before: str.endIndex))
// str = hello world
//长度
let range = str.index(str.endIndex, offsetBy: -6)..<str.endIndex
str.removeSubrange(range)
// str = hello
}
//创建
var a = [1,2,3]
var b: [String] = ["1","2"]
var c : Array<Double> = [1.3,2.3]
var d = Array(repeating: -1,count: 3)//初始值是-1 长度为3
//增
a += [4]//[1,2,3,4]
a.append(5)//[1,2,3,4,5]
//删
a.remove(at: 0) // [2,3,4,5]
//改
a[0] = 6
//查
a[0]
//插
a.insert(6,at: 3) //[6, 3, 4, 6, 5]
//排序
var array = ["A","B","C","D","E","F"]
array.sort { (s1, s2) -> Bool in
if s1>s2 {
return true
} else {
return false;
}
}
//过滤 过滤掉"D"
array.filter { (item) -> Bool in
item == "D"
}
//数组的比较
var array1 = [1,2,3]
var array2 = [1,2,3]
if array1 == array2 {
print("相等")
}else{
print("不相等")
}
//遍历
var array3 = [1,2,3]
for item in array3 {
print(item)//每个数组中的元素的值
}
for index in 0..<array3.count {
print(array3[index])
}
var set1 = Set<Character>() //空集合
var setList = ["A","B","C"]
//长度
setList.count
//插入
setList.insert("D", at: setList.endIndex)//["A","B","C","D"]
//删除
setList.remove(at: 0)//["B","C","D"]
//是否包含
setList.contains("B")
//合并
let setA: Set<Int> = [1, 3, 5, 7, 9, 8]
let setB: Set<Int> = [0, 2, 4, 6, 8]
let setC: Set<Int> = [2, 3, 5, 7]
// 方法根据两个集合的所有值创建一个新的集合 重复的会合并
setA.union(setB).sorted() // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//根据两个集合的交集创建一个新的集合
setA.intersection(setB).sorted() // []
//不在另一个集合中的值创建一个新的集合
setA.subtracting(setC).sorted() // [1, 8, 9]
//根据两个集合不相交的值创建一个新的集合。
setA.symmetricDifference(setC).sorted() // [1, 2, 8, 9]
// 遍历
for item in setList {
print("\(item)")
}
// 有序遍历
var setListB = ["2","3","1","5","4"]
for item in setListB.sorted() {
print("\(item)")
}
let setD: Set<String> = ["A", "B"]
let setE: Set<String> = ["C", "E", "F", "A", "B"]
let setF: Set<String> = ["G", "H"]
//判断setD中的所有值是否也被包含在setE
setD.isSubset(of: setE) // true
//判断setE是否包含setD中所有的值。
setE.isSuperset(of: setD) // true
//setE setF 是否没有交集
setE.isDisjoint(with: setF)// true
//创建
var a: Dictionary<String,String> = [:]
var b: [String: String] = [:]
var c = [Int: String]();
//基本操作
a["1"] = "A"; //赋值
a["1"] = "B"//修改
a["2"] = "C"//增加
a["3"] = "D"//增加
//删除
a.removeValue(forKey: "2")
//a.remove(at: a.startIndex)
//获取keys values
let keyList = [String](a.keys)
let valueList = [String](a.values)
//过滤
a.filter { (key, value) -> Bool in
if (key == "a") {
return false
}
return true
}
//循环遍历
for (key,value) in a {
//循环出key和value
print(key + ":" + value)
}
//1. for-in
let chars = ["a", "b", "c", "d"]
for char in chars {
print(char)
}
//
let person = ["age": 8, "weight": 130, "heigh": 170]
for (key, value) in person {
print("\(key) : \(value)")
}
//
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 2. While 循环
//While
var i = 0;
while i < 5 {
i += 1
print(i)
}
// repeat-while
var j = 0;
// 先执行后判断
repeat{
j += 1;
print(j)
}while j<5
//3. if
if i>j{
} else if i>j {
}else{
}
//4. switch
// 4.1 元组 _表示可能的值
let point = (1, 1)
switch point {
case (0, 0):
print("\(point) 在原点")
case (_, 0):
print("\(point) 在X轴")
case (0, _):
print("\(point) 在Y轴")
case (-2...2, -2...2):
print("\(point) 在正方形内部")
default:
print("\(point) 在正方形外部")
}
//4.2 值绑定 case 分支允许将匹配的值声明为临时常量或变量,并且在 case 分支体内使用
let point1 = (2, 0)
switch point1 {
case (let x, 0):
print("x : \(x)")
case (0, let y):
print("y :\(y)")
case let (x, y):
print("点 在 (\(x), \(y))")
}
//4.3 Where where 语句来判断额外的条件
let point2 = (1, -1)
switch point2 {
case let (x, y) where x == y:
print("(\(x), \(y)) 在 x == y 上")
case let (x, y) where x == -y:
print("(\(x), \(y)) 在 x == -y 上")
case let (x, y):
print("(\(x), \(y))")
}
// 4.5
//continue 立刻停止本次循环,重新开始下次循环
//break 结束整个循环
//fallthrough 语句让 case 之后的语句会按顺序继续运行,且不论条件是否满足都会执行。
//return 直接返回
// guard xxx else { return } xxx 条件为假 执行else
//throw 抛出错误
//1,函数的定义
func test() {
print("123")
}
//带返回参数(int)的函数 可以被写成一行 return 语句的函数都可以忽略 return。
func test() -> Int {
3
}
//带返回参数(int)和参数(string)的函数
func test(value: String) -> Int{
print(value)
return 3
}
//可变参数
func test(value: String...) {
//是个数组
for item in value {
print(item)
}
}
//关于 参数名称
func test(firstValue secondValue: String) {
}
//调用
test(firstValue: "test")
//_符号忽略外部名称 (外部名称和内部名称不能互用 内部名称不能忽略)
func test(_ name: String){
}
test("123")
// 输入输出 函数 inout 标志 外部参数 可以在函数内部改变
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var a = 3
var b = 107
swapTwoInts(&a, &b); // a = 107 b = 3
//嵌套函数
func outFunc(backward: Bool) -> (Int) -> Int {
func insideFuncA(input: Int) -> Int { return input + 1 }
func insideFuncB(input: Int) -> Int { return input - 1 }
return backward ? insideFuncB : insideFuncA
}
var num = -6
let funcC = outFunc(backward: num > 0)
// moveNearerToZero now refers to the nested stepForward() function
while num != 0 {
print("\(num)")
num = funcC(num)
}
// -6 -5 -4 -3 -2 -1
// 语法
//{(parameters) -> return type in
// statements
//}
let chars = ["C", "A", "E", "B", "D"]
//函数
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var reversedChars = chars.sorted(by: backward)
// 闭包
reversedChars = chars.sorted(by: { (s1: String, s2: String) -> Bool in
return s1<s2
})
//简写 参数名称简写 $0 代表第一个参数 。。 单行表达式 省略return
reversedChars = chars.sorted(by: { $0 > $1 } )
/*Swift 的 String 类型定义了关于大于号(<)的字符串实现,
其作为一个函数接受两个 String 类型的参数并返回 Bool 类型的值。
而这正好与 sorted(by:) 方法的参数需要的函数类型相符合。
因此,可以简单地传递一个大于号,
Swift 可以自动推断找到系统自带的那个字符串函数的实现*/
reversedChars = chars.sorted(by: < )
//尾随闭包
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {
(number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
//逃逸闭包 逃逸闭包的生命周期是长于函数的。
func getData(closure:@escaping (Any) -> Void) {
print("函数开始执行--\(Thread.current)")
DispatchQueue.global().async {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2, execute: {
print("执行了闭包---\(Thread.current)")
closure("123")
})
}
print("函数执行结束---\(Thread.current)")
}
getData { (data) in
print("闭包结果返回--\(data)--\(Thread.current)")
}
//定义
enum test {
case A
case B
case C
}
print(test.A)
//设置枚举初始值
enum test1: Int {
case A = 1
case B = 2
}
print(test1.A.rawValue)
//遍历枚举
//令枚举遵循 CaseIterable 协议。
//Swift 会生成一个 allCases 属性,用于表示一个包含枚举所有成员的集合
enum test2: CaseIterable{
case A //0
case B//1
}
//拿到case数组 然后遍历就行了
var list = test2.allCases;
// 结构体是值类型 赋值给其它对象时 值会被拷贝
struct Resolution {
var width = 0
var height = 0
}
let vga = Resolution(width: 640, height: 480)
var cinema = vga
cinema.width = 2048
print(vga.width) //640
print(cinema.width) //2048
// 类是引用类型
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
let tenEighty = VideoMode()
tenEighty.resolution = vga
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
print(tenEighty.frameRate) //30.0
print(alsoTenEighty.frameRate) //30.0
// 结构体是值类型 赋值给其它对象时 值会被拷贝
struct Resolution {
var width = 0
var height = 0
}
let vga = Resolution(width: 640, height: 480)
var cinema = vga
cinema.width = 2048
print(vga.width) //640
print(cinema.width) //2048
// 类是引用类型
class VideoMode {
var resolution = Resolution()
var interlaced = false
var name: String = ""
var frameRate = 0.0
var size : Resolution {
get {
Resolution(width: resolution.width, height: resolution.height)
}
set {
resolution.width = newValue.width
resolution.height = newValue.height
}
}
var totalSteps : Int = 0 {
// set 之前调用
willSet(newTotalSteps) {
print("将 totalSteps 的值设置为 \(newTotalSteps)")
}
// set 之后调用
didSet {
if totalSteps > oldValue {
print("增加了 \(totalSteps - oldValue) 步")
}
}
}
}
let tenEighty = VideoMode()
tenEighty.resolution = vga
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
print(tenEighty.size) //Resolution(width: 640, height: 480)
tenEighty.size = Resolution(width: 100, height: 100)
print(tenEighty.size) //Resolution(width: 100, height: 100)
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
print(tenEighty.frameRate) //30.0
print(alsoTenEighty.frameRate) //30.0
alsoTenEighty.totalSteps = 200
// 将 totalSteps 的值设置为 200
// 增加了 200 步
All paths through this function will call itself
报这个错,计算属性是根据其他存储属性去计算获得值。它自己不直接存储值,都是间接获取和设置其他属性或变量的值