在 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
,你可以為現有型別新增新的功能,而無需繼承或修改原始型別。這使得程式碼更加模組化和易於維護。