# swift基础之扩展现有类、结构体、枚举

2021/04/16 11:08

## 扩展计算属性

//扩展 Double 计算属性
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}

let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
//One inch is 0.0254 meters

let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
//Three feet is 0.914399970739201 meters


## 扩展初始化器

//扩展初始化器
struct Rect{
var x = 0.0, y = 0.0
var width = 0.0, height = 0.0
}

extension Rect {
init(pos: [Double], size: [Double]) {
self.init(x: pos[0], y: pos[1], width: size[0], height: size[1])
}
}

let r = Rect(pos: [0.0, 0.0], size: [4.0, 4.0])


## 扩展方法

//扩展方法
extension Int {
func repeatTalk(talk: () -> Void) {
for _ in 0..<self {
talk()
}
}
}

5.repeatTalk {
print("Hi")
}
/*
Hi
Hi
Hi
Hi
Hi
*/


## 修改实例本身 mutating

//修改实例本身 mutating
extension Int {
mutating func square() {
self = self * self
}
}

var a = 5
a.square()
print(a)
//25


## 扩展下标

//扩展下标
extension Int {
subscript(index: Int) -> Int {
var base = 1
for _ in 0..<index {
base *= 10
}
return (self/base) % 10
}
}
print(12345678[0])
print(12345678[1])
print(12345678[2])
print(12345678[3])
print(12345678[4])
/*
8
7
6
5
4
*/


## 扩展内嵌类型

//扩展内嵌类型
extension Int {
enum Kind {
case negative, zero, positive
}

var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}

print(4.kind)
//positive


0 评论
0 收藏
0