在 Swift 中,extension
关键字用于为现有的类、结构体、枚举或协议添加新的功能,而无需修改原始源代码。扩展可以添加新的方法、计算属性、初始化器、下标、嵌套类型和遵循协议等。
以下是一些常见的 extension
用法示例:
为类添加方法
extension String {
func reversedString() -> String {
return String(self.reversed())
}
}
let original = "Hello"
let reversed = original.reversedString() // "olleH"
为结构体添加计算属性
struct Point {
var x: Double
var y: Double
}
extension Point {
var magnitude: Double {
return (x * x + y * y).squareRoot()
}
}
let point = Point(x: 3, y: 4)
let magnitude = point.magnitude // 5.0
为枚举添加初始化器
enum Direction {
case north, south, east, west
}
extension Direction {
init?(abbreviation: String) {
switch abbreviation.lowercased() {
case "n": self = .north
case "s": self = .south
case "e": self = .east
case "w": self = .west
default: return nil
}
}
}
let direction = Direction(abbreviation: "n") // .north
为协议添加默认实现
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello!")
}
}
struct Person: Greetable {}
let person = Person()
person.greet() // "Hello!"
为类添加协议遵循
protocol Describable {
var description: String { get }
}
extension Int: Describable {
var description: String {
return "The number is \(self)"
}
}
let number = 42
print(number.description) // "The number is 42"
为泛型类型添加扩展
extension Array where Element: Equatable {
func containsDuplicates() -> Bool {
for (index, element) in self.enumerated() {
if self[index + 1...].contains(element) {
return true
}
}
return false
}
}
let array = [1, 2, 3, 1]
let hasDuplicates = array.containsDuplicates() // true
通过使用 extension
,你可以为现有类型添加新的功能,而无需继承或修改原始类型。这使得代码更加模块化和易于维护。