当前位置:网站首页>Swift 扩展
Swift 扩展
2022-06-09 05:21:00 【same_life】
扩展的概念
- 扩展就是向现有的类、结构体、枚举类型、或协议添加新的功能。
- 扩展可以对一个类型添加新的功能,但是不能重写已有的功能。
- 扩展和 Objective-C 中的 category 类似。(与 Objective-C 的分类不同的是,Swift 的扩展没有名 字。)
扩展的功能
- 添加计算实例属性和计算类型属性
- 定义实例方法和类型方法
- 提供新初始化器
- 定义下标
- 定义和使用新内嵌类型
- 使现有的类型遵循某协议
- 扩展可以向一个类型添加新的方法,但是不能重写已有的方法
扩展的语法
- 声明扩展使用 extension 关键字
extension SomeType {
// 需要扩展的 SomeType 的新功能
}
- 一个扩展可以扩展一个已有类型,使其能够适配一个或多个协议,语法格式如下:
extension SomeType: SomeProtocol, AnotherProtocol {
// 协议实现
}
计算属性
- 扩展可以向已有的类型添加计算实例属性和计算类型属性。
//向 Double 类型添加了 4 个计算型实例属性并扩展其功能
extension Double {
var km: Double {
return self * 1000.0 }
var m: Double {
return self }
var cm: Double {
return self / 100.0 }
var mm: Double {
return self / 10000.0 }
}
let num1 = 1.2.km
print("num1 is \(num1) meters")
let num2 = 250.cm
print("num2 is \(num2) meters")
初始化器
- 扩展可向已有的类型添加新的初始化器。这允许你扩展其他类型以使初始化器接收你的自定义类型作为形式参数,或提供该类型的原始实现中未包含的额外初始化选项。
- 扩展能为类添加新的便捷初始化器,但是不能为类添加指定初始化器或反初始化器。指定初始化器 和反初始化器 必须由原来类的实现提供。
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
extension Rect {
//向已有的类型添加新的初始化器
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4, y: 4), size: Size(width: 3, height: 3))
方法
- 扩展可以为已有的类型添加新的实例方法和类型方法。
//为实例方法添加扩展
extension Int {
func repititions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repititions {
print("hello")
}
/** 打印: hello hello hello */
mutating 方法
- 扩展的实例方法仍可以修改(或异变)实例本身。结构体和枚举类型方法在修改 self 或本身的属性时必须标记实例方法为 mutating ,和原本实现的异变方法一样。
//异变方法
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
print(someInt) // 9
下标
- 扩展能为已有的类型添加新的下标。
extension Int {
subscript(digitalIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitalIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
746381295[0] // 5
746381295[1] // 9
746381295[2] // 2
746381295[8] // 7
添加内嵌类型
- 扩展可以为已有的类、结构体和枚举类型添加新的内嵌类型。
extension Int {
enum Kind {
case negative, zero, pozitive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .pozitive
default:
return .negative
}
}
}
print(3.kind) // pozitive
边栏推荐
- STM32 FreeRTOS task Basics
- Kube dns yaml
- AI video cloud: a good wife in the era of we media
- Leetcode 1037.有效的回旋镖
- Alibaba cloud AI training camp MySQL foundation 1:
- Leetcode 929.独特的电子邮件地址
- Intranet penetration hash delivery attack
- Previous improvements of CSDN products (up to issue 29)
- 2022 welder (elementary) special operation certificate examination question bank and simulation examination
- Detailed introduction to arrays and linked lists
猜你喜欢

内网渗透 - 哈希传递攻击

Mysql5.7 dual master and dual slave configuration

Alibaba cloud AI training camp - SQL basics 3: complex query methods - views, subqueries, functions, etc

How to build fastdfs, vsftpd and miniio file servers in marathon environment

PS how to border an image

三方账号授权登录系统设计思路

MQ message loss, message consistency, repeated consumption solution

Li Kou today's question -1037 Effective boomerang

Mécanisme de mise en cache dans le transformateur

Stack
随机推荐
Alibaba cloud AI training camp -sql basics 5: window functions, etc
Transformer裏面的緩存機制
Thinking of reading
groupby函数详解
Camtasia studio2022 free key serial number installation trial detailed graphic tutorial
AspNetPager combines stored procedure paging to speed up access
Requests segmented downloading of files and multi-threaded downloading
“Ran out of input” while use WikiExtractor
The principle and implementation of lazy image loading
STM32 FreeRTOS task Basics
Load research of Marathon LB
Mysql5 available clusters
2022 welder (elementary) special operation certificate examination question bank and simulation examination
^25进程与线程
PS how to border an image
Lucene构建索引与执行搜索小记
reids 缓存与数据库数据不一致、缓存过期删除问题
[it] Fuxin PDF Keeping Tool Selection
Alibaba cloud AI training camp -sql basics 6: test questions
Differences between tinyint and int