100swift技巧
### 100swift技巧详解####一、Selector **知识点:** - **Selector**是Objective-C中用于表示消息传递的一种方式,在Swift中也可以通过`#selector`来使用。 - Selector可以用来作为方法的引用,这对于实现回调、事件响应等功能非常有用。 **示例:** ```swift let button = UIButton() button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) @objc func buttonTapped(sender: UIButton) { print("Button was tapped") } ``` ####二、柯里化(Currying) **知识点:** - **柯里化**是一种将多参数函数转换为一系列单参数函数的技术。 -在Swift中可以通过定义接受闭包作为参数或者返回闭包的方式来实现柯里化。 **示例:** ```swift func add(a: Int) -> (Int) -> Int { return { b in return a + b } } let addTwo = add(a: 2) print(addTwo(3)) //输出5 ``` ####三、将protocol的方法声明为mutating **知识点:** -在Swift中,如果一个协议中的方法需要修改self,那么应该将其声明为`mutating`。 -这样做可以确保任何实现该协议的结构体都必须使用`mutating`关键字。 **示例:** ```swift protocol MyProtocol { mutating func doSomething() } struct MyStruct: MyProtocol { var value: Int = 0 mutating func doSomething() { self.value += 1 } } ``` ####四、Sequence **知识点:** - Swift提供了多种序列类型,如Array、Set等。 -序列类型支持基本的操作,如`map`、`filter`、`reduce`等。 **示例:** ```swift let numbers = [1, 2, 3, 4, 5] let evenNumbers = numbers.filter { $0 % 2 == 0 } print(evenNumbers) //输出[2, 4] ``` ####五、多元组(Tuple) **知识点:** - **Tuple**是Swift中一种集合多个值的复合数据类型。 - Tuple中的元素可以是不同类型的,并且可以通过索引或名称来访问。 **示例:** ```swift let student = ("Tom", 22, "Computer Science") print(student.0) //输出Tom print(student.2) //输出Computer Science ``` ####六、@autoclosure和?? **知识点:** - `@autoclosure`是一个属性包装器,它将表达式延迟到实际使用时才计算。 - `??`操作符称为“nil合并”操作符,用于提供一个默认值。 **示例:** ```swift func safeDivide(numerator: Int, denominator: @autoclosure Int) -> Int { let denominatorValue = denominator() guard denominatorValue != 0 else { return 0 } return numerator / denominatorValue } print(safeDivide(numerator: 10, denominator: 5)) //输出2 print(safeDivide(numerator: 10, denominator: 0 ?? 5)) //输出2 ``` ####七、Optional Chaining **知识点:** - **Optional chaining**允许安全地访问链式属性或方法调用,即使其中一个环节为nil也不会崩溃。 -使用`?.`来尝试访问属性或方法。 **示例:** ```swift let user = ["name": "Alice"] if let name = user["name"] { print(name) //输出Alice } else { print("Name not found") } ``` ####八、操作符**知识点:** - Swift提供了丰富的内置操作符,包括算术、逻辑、比较等。 -用户还可以定义自定义操作符。 **示例:** ```swift //定义一个新的操作符infix operator ** {} //实现操作符func ** (base: Int, exponent: Int) -> Int { return Int(pow(Double(base), Double(exponent))) } print(2 ** 3) //输出8 ``` ####九、func的参数修饰**知识点:** - Swift中的函数可以使用各种参数修饰符,如`in`、`out`、`inout`等。 -这些修饰符定义了函数如何与外部作用域进行交互。 **示例:** ```swift func swapValues(_ a: inout Int, _ b: inout Int) { let temp = a a = b b = temp } var x = 1 var y = 2 swapValues(&x, &y) print("x is now (x), and y is now (y)") //输出x is now 2, and y is now 1 ``` ####十、方法参数名称省略**知识点:** -在调用函数或方法时,Swift允许省略某些参数名称,以简化调用。 -当参数列表中的参数名称与方法签名中的参数名称相同时,可以省略参数名称。 **示例:** ```swift func greet(to person: String) { print("Hello, (person)!") } greet(to: "Bob") //调用时可以省略参数名称```以上是本书籍的部分知识点概述,这些技巧涵盖了从基础到高级的多个方面,旨在帮助读者更好地理解和应用Swift语言特性。
1.61MB
文件大小:
评论区