当前位置:网站首页>Swift extension
Swift extension
2022-06-09 05:27:00 【same_ life】
Extended concept
- Extension is to extend an existing class 、 Structure 、 Enumeration type 、 Or protocol to add new features .
- Extensions can add new functionality to a type , But you can't rewrite existing functions .
- Extension and Objective-C Medium category similar .( And Objective-C The different classification is ,Swift No extension for word .)
Extended functionality
- Add calculation instance properties and calculation type properties
- Define instance methods and type methods
- Provide a new initializer
- Define subscripts
- Define and use new inline types
- Make existing types conform to a protocol
- Extensions can add new methods to a type , But you can't override existing methods
Extended syntax
- Declare that the extension uses extension keyword
extension SomeType {
// Need to expand SomeType New functions
}
- An extension can extend an existing type , Enable it to adapt to one or more protocols , The syntax is as follows :
extension SomeType: SomeProtocol, AnotherProtocol {
// Protocol implementation
}
Compute properties
- Extensions can add calculation instance properties and calculation type properties to existing types .
// towards Double Type added 4 Compute instance properties and extend their functions
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")
The initializer
- Extensions can add new initializers to existing types . This allows you to extend other types so that the initializer receives your custom type as a formal parameter , Or provide additional initialization options not included in the original implementation of the type .
- Extension can add new convenient initializers to classes , However, you cannot add a specified initializer or de initializer to a class . Specify initializer And de initializer Must be provided by the implementation of the original class .
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 {
// Add a new initializer to an existing type
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))
Method
- Extensions can add new instance methods and type methods to existing types .
// Add extensions to instance methods
extension Int {
func repititions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repititions {
print("hello")
}
/** Print : hello hello hello */
mutating Method
- The extended instance method can still be modified ( Or change ) The instance itself . Structure and enumeration type methods are being modified self Or its own properties, the instance method must be marked as mutating , It's the same as the variation method originally implemented .
// Mutation method
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
print(someInt) // 9
Subscript
- Extensions can add new subscripts to existing types .
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
Add inline type
- The extension can be an existing class 、 Structure and enum types add new inline types .
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
边栏推荐
- AQS 之 CyclicBarrier 源码分析
- Codeigniter3 learning notes 5 (form verification)
- PS how to add white edges to images
- Heap and priority queues
- Requests segmented downloading of files and multi-threaded downloading
- myql报错 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
- When classical music meets NFT
- TCP error control, flow control, congestion control
- reids 缓存与数据库数据不一致、缓存过期删除问题
- ps如何给图像加边框
猜你喜欢
随机推荐
Cloud computing technology
wps ppt背景图片如何换颜色
[django learning notes - 12]: database operation
Pull down the new project code and make it red
Alibaba cloud AI training camp - machine learning 2:xgboost
latex中\cdots后面接上句子,后面的句子格式会乱怎么回事。
3-4月份我们干了些什么?
Analysis of reentrantlock source code of AQS
Encapsulation of common methods in projects
ps如何给图像加边框
Alibaba cloud AI training camp - SQL basics 4: set operation - addition and subtraction of tables, join, etc
Pattern recognition big job PCA & Fisher & KNN & kmeans
MQ message loss, message consistency, repeated consumption solution
AI video cloud: a good wife in the era of we media
How to change the color of WPS ppt background picture
The principle and implementation of lazy image loading
MarathonLb的负载研究
ps如何给图像加白边
Windows uses php to start ThinkPHP project and deploy configuration
readme. md









