1. 基本语法
extension Type {
// 添加新功能
}
2. 扩展计算属性
extension Double {
var squared: Double {
return self * self
}
}
let number = 4.0
let squaredNumber = number.squared // 16.0
3. 扩展方法
extension String {
func greet() {
print("Hello, \(self)!")
}
}
let name = "John"
name.greet() // 输出: Hello, John!
4. 扩展构造函数
extension Int {
init(fromString str: String) {
self = Int(str) ?? 0
}
}
let stringNumber = "42"
let intValue = Int(fromString: stringNumber) // 42
5. 扩展协议
protocol Vehicle {
func start()
}
extension Vehicle {
func stop() {
print("Vehicle stopped.")
}
}
struct Car: Vehicle {
func start() {
print("Car started.")
}
}
let myCar = Car()
myCar.start() // 输出: Car started.
myCar.stop() // 输出: Vehicle stopped.
6. 扩展嵌套类型
struct Container {
var items: [Int]
struct Iterator {
private var index = 0
mutating func getNext() -> Int? {
guard index < items.count else { return nil }
defer { index += 1 }
return items[index]
}
}
}
extension Container.Iterator {
init(_ items: [Int]) {
self.init()
self.items = items
}
}
let container = Container(items: [1, 2, 3])
var iterator = Container.Iterator(container.items)
while let nextItem = iterator.getNext() {
print(nextItem)
}
这些示例展示了 Swift 扩展的一些常见用法,但这只是冰山一角。Swift 的扩展功能非常灵活,可以用于许多其他情景。
转载请注明出处:http://www.zyzy.cn/article/detail/6860/Swift