swift Extensions(官方文档翻译)
Extensions add new functionality to an existing class,structure,enumeration,or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories,Swift extensions do not have names.) Extensions in Swift can: In Swift,you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details,see Protocol Extensions. NOTE Extension Syntax(语法)Declare extensions with the extension keyword: extension SomeType {
// new functionality to add to SomeType goes here
}
An extension can extend an existing type to make it adopt one or more protocols. Where this is the case,the protocol names are written in exactly the same way as for a class or structure: extension SomeType: SomeProtocol,AnotherProtocol {
// implementation of protocol requirements goes here
}
Adding protocol conformance in this way is described in Adding Protocol Conformance with an Extension. NOTE Computed Properties(计算属性)Extensions can add computed instance properties and computed type properties to existing types. This example adds five computed instance properties to Swift’s built-in Double type,to provide basic support for working with distance units: 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")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is (threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"
These computed properties express that a Double value should be considered as a certain unit of length. Although they are implemented as computed properties,the names of these properties can be appended to a floating-point literal value with dot syntax,as a way to use that literal value to perform distance conversions. In this example,a Double value of 1.0 is considered to represent “one meter”. This is why the m computed property returns self—the expression 1.m is considered to calculate a Double value of 1.0. Other units require some conversion to be expressed as a value measured in meters. One kilometer is the same as 1,000 meters,so the km computed property multiplies the value by 1_000.00 to convert into a number expressed in meters. Similarly,there are 3.28084 feet in a meter,and so the ft computed property divides the underlying Double value by 3.28084,to convert it from feet to meters. These properties are read-only computed properties,and so they are expressed without the get keyword,for brevity. Their return value is of type Double,and can be used within mathematical calculations wherever aDouble is accepted: let aMarathon = 42.km + 195.m
print("A marathon is (aMarathon) meters long")
// prints "A marathon is 42195.0 meters long”
NOTE Initializers(构造方法)Extensions can add new initializers to existing types. This enables you to extend other types to accept your own custom types as initializer parameters,or to provide additional initialization options that were not included as part of the type’s original implementation. Extensions can add new convenience initializers to a class,but they cannot add new designated initializers or deinitializers to a class. Designated initializers and deinitializers must always be provided by the original class implementation. NOTE This would not be the case if you had written the initializer as part of the value type’s original implementation,as described in Initializer Delegation for Value Types. 注意 不包含这种情况,你已经重写了该值类型的初始化器。参考 INITIALIZER DELEGATION FOR VALUE TYPES. The example below defines a custom Rect structure to represent a geometric rectangle. The example also defines two supporting structures called Size and Point,both of which provide default values of 0.0 for all of their properties: 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()
}
Because the Rect structure provides default values for all of its properties,it receives a default initializer and a memberwise initializer automatically,as described in Default Initializers. These initializers can be used to create new Rect instances: 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)
}
}
This new initializer starts by calculating an appropriate origin point based on the provided center point andsize value. The initializer then calls the structure’s automatic memberwise initializer init(origin:size:),which stores the new origin and size values in the appropriate properties: let centerRect = Rect(center: Point(x: 4.0,y: 4.0),size: Size(width: 3.0,height: 3.0))
// centerRect's origin is (2.5,2.5) and its size is (3.0,3.0)
NOTE Methods(方法)Extensions can add new instance methods and type methods to existing types. The following example adds a new instance method called repetitions to the Int type: extension Int {
func repetitions(task: () -> Void) { for _ in 0..<self { task() } } }
The repetitions(_:) method takes a single argument of type () -> Void,which indicates a function that has no parameters and does not return a value. After defining this extension,you can call the repetitions(_:) method on any integer number to perform a task that many number of times: 3.repetitions({
print("Hello!")
})
// Hello!
// Hello!
// Hello!
Use trailing closure syntax to make the call more succinct: 3.repetitions {
print("Goodbye!")
}
// Goodbye!
// Goodbye!
// Goodbye!
Mutating Instance Methods(用Mutating修饰的实例方法)Instance methods added with an extension can also modify (or mutate) the instance itself. Structure and enumeration methods that modify self or its properties must mark the instance method as mutating,just like mutating methods from an original implementation. The example below adds a new mutating method called square to Swift’s Int type,which squares the original value: extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
// someInt is now 9
Subscripts(下标/索引)Extensions can add new subscripts to an existing type. This example adds an integer subscript to Swift’s built-in Int type. This subscript [n] returns the decimal digit n places in from the right of the number: Extensions可以为现有类添加新的下标语义,实例中是从右边开始: 123456789[0] returns 9
123456789[1] returns 8
…and so on: extension Int {
subscript(var digitIndex: Int) -> Int {
var decimalBase = 1
while digitIndex > 0 {
decimalBase *= 10
--digitIndex
}
return (self / decimalBase) % 10
}
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7
If the Int value does not have enough digits for the requested index,the subscript implementation returns 0,as if the number had been padded with zeros to the left: 746381295[9]
// returns 0,as if you had requested:
0746381295[9]
Nested Types(内部类)
Extensions can add new nested types to existing classes,structures and enumerations: 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
}
}
}
This example adds a new nested enumeration to Int. This enumeration,called Kind,expresses the kind of number that a particular integer represents. Specifically,it expresses whether the number is negative,zero,or positive. This example also adds a new computed instance property to Int,called kind,which returns the appropriateKind enumeration case for that integer. The nested enumeration can now be used with any Int value: func printIntegerKinds(numbers: [Int]) {
for number in numbers {
switch number.kind {
case .Negative:
print("- ",terminator: "")
case .Zero:
print("0 ",terminator: "")
case .Positive:
print("+ ",terminator: "")
}
}
print("")
}
printIntegerKinds([3,19,-27,0,-6,7])
// prints "+ + - 0 - 0 +"
This function,printIntegerKinds,takes an input array of Int values and iterates over those values in turn. For each integer in the array,the function considers the kind computed property for that integer,and prints an appropriate description. NOTE number.kind is already known to be of type Int.Kind. Because of this,all of the Int.Kind case values can be written in shorthand form inside the switch statement,such as .Negative rather thanInt.Kind.Negative. 注意 简写 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- C#递归遍历窗体所有textbox控件并设置textbox事件的方法
- 在POstgreSQL中创建 数据库 带 编码
- cocos2d-x 3.8.1的骨骼动画加载方法addArmatureFileInfo仍然
- 基础算法7:使用正则提取网页中a标签的链接和标题
- org.xml.sax.SAXParseException: The content of elements
- c# – Unity Container Resolve
- .net – LINQ to XML:如何才能得到XElement的直接后代?
- ruby-on-rails – 从引擎内重定向到父Rails应用程序的路由
- Oracle 的加减法函数
- vue获取dom元素注意事项