swift Extensions(官方文档翻译)

swift Extensions(官方文档翻译),第1张

概述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

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 为现有类添加结构体(structure),枚举(enumeration),协议(protocol),这使你可以在不能访问源码的情况下扩展功能(又称逆向建模)。它和OC中的categorIEs类似,但是它没有名字

Extensions in Swift can:
1.Add computed propertIEs and computed type propertIEs
2.define instance methods and type methods
3.ProvIDe new initializers
4.define subscripts
5.define and use new nested types
6.Make an existing type conform to a protocol
用处:
1.添加计算属性和计算类属性
2.定义实例方法和类方法
3.提供新的构造方法
4.定义subscripts(下标?)
5.定义和使用新的内部类
6.是现有类实现一个协议

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.
在swift中,你甚至可以为协议提供扩展功能,这样实现类就可以实现新的需求或者添加额外的方法(Protocol Extensions)。

NOTE
Extensions can add new functionality to a type,but they cannot overrIDe existing functionality.
注意
Extensions 可以添加新的方法,但是不可以重写

Extension Syntax(语法)

Declare extensions with the extension keyword:
使用extension 关键字声明Extensions

extension SomeType {    @H_404_37@// 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:
一个Extensions 可以为现有类实现一个或多个协议,这种情况下,写法和类、结构体一样

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.
这种方式添加协议,可参考 Adding Protocol Conformance with an Extension.

NOTE
If you define an extension to add new functionality to an existing type,the new functionality will be available on all existing instances of that type,even if they were created before the extension was defined.
注意
如果你为现有类添加了一个新的Extensions,包含新的功能,即便是创建该类的对象在定义扩展之前,该对象也有扩展的功能。

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:
Extensions可以为现有类添加计算实例属性和计算类属性,这个示例为swift内置的Double类添加了5个计算示例属性,添加了距离单位功能。

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.mmprint("One inch is \(oneInch) meters")@H_404_37@// prints "One inch is 0.0254 meters"let threeFeet = 3.ftprint("Three feet is \(threeFeet) meters")@H_404_37@// 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.
这些计算属性使一个double类型的值作为长度的某个单位,尽管他们作为计算属性,浮点字面值,也可以用点语法,来调用它们,通过这种方式使字面值实现距离转换。

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.
在这个例子中,double类型1.0代表”1米”,这是m计算属性return self的原因—表达式1.m,其实是对double值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.
其他的距离单位需要一些转换,以单位米为标准,1KM=1000m,所以km计算属性是通过乘以1000,来得到以米为单位的结果。类似的,1m=3.28084ft

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:
这些计算属性都是只读的,为了简洁,所以没有get关键字。返回值是Double类型,只要是double类型,可以在任何地方,使用这些数学计算。

let aMarathon = 42.km + 195.mprint("A marathon is \(aMarathon) meters long")@H_404_37@// prints "A marathon is 42195.0 meters long”

NOTE
Extensions can add new computed propertIEs,but they cannot add stored propertIEs,or add property observers to existing propertIEs.
注意
Extensions 可以添加新的计算属性,但他不可以添加存储属性,或者添加新的属性来监听现有属性

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 可以为现有类添加构造方法,这使你可以新的构造方法传递参数,或者为构造方法提供其他的选项。

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.
Extensions可以为一个类添加一个便捷的构造方法,但是不可以添加指定初始化器(designated initializer),指定初始化器只能被初始类实现。

NOTE
If you use an extension to add an initializer to a value type that provIDes default values for all of its stored propertIEs and does not define any custom initializers,you can call the default initializer and memberwise initializer for that value type from within your extension’s initializer.

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:
示例中自定义了一个Rect结构体来描述一个矩形,也同时定义了Size,Point结构体,所有的属性默认值是0.0

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:
因为Rect为其所有的属性提供了默认值,所以它可以自动提供指定初始化器和属性逐一初始化器,参考Default Initializers。可以通过这些初始化器创建一个Rect实例:
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0,y: 2.0),
size: Size(wIDth: 5.0,height: 5.0))
You can extend the Rect structure to provIDe an additional initializer that takes a specific center point and size:
你可以添加一个Extensions 为其添加一个通过center和size创建一个Rect的初始化方法:

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
If you provIDe a new initializer with an extension,you are still responsible for making sure that each instance is fully initialized once the initializer completes.
注意
在扩展的初始化方法中,调用原始初始化方法。

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:
Extensions可以为现有类添加实例方法和类方法,实例为Int类添加了一个叫repetitions的实例方法。

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.
repetitions(_:)只有一个参数() -> VoID,并且这个参数(函数/闭包)没有参数和返回值

After defining this extension,you can call the repetitions(_:) method on any integer number to perform a task that many number of times:
在定义了这个Extension之后,任何整数类型(值为3)调用repetitions(_:)都会调用task对应的次数(3次)

3.repetitions({    print("Hello!")})@H_404_37@// Hello!@H_404_37@// Hello!@H_404_37@// Hello!

Use trailing closure Syntax to make the call more succinct:
使用尾随闭包语法,使其更简洁:

3.repetitions {    print("Goodbye!")}@H_404_37@// Goodbye!@H_404_37@// Goodbye!@H_404_37@// 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.
通过extension添加的实例方法也可以修改实例本身,结构体和枚举的方法必须用mutating来修饰,就像原始实现一样。

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 = 3someInt.square()@H_404_37@// 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 9123456789[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]@H_404_37@// returns 5746381295[1]@H_404_37@// returns 9746381295[2]@H_404_37@// returns 2746381295[8]@H_404_37@// 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:
如果Int值得位数小于索引值,就会返回0,就像在int值的左边添加了0一样:

746381295[9]@H_404_37@// returns 0,as if you had requested:0746381295[9]nested Types(内部类)

Extensions can add new nested types to existing classes,structures and enumerations:
Extensions可以在类,结构体,枚举中添加添加内部类:

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. 注意 简写

总结

以上是内存溢出为你收集整理的swift Extensions(官方文档翻译)全部内容,希望文章能够帮你解决swift Extensions(官方文档翻译)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1082552.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存