swift Extensions(官方文档翻译)

翻译 2015年11月21日 18:29:09

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 {
    // 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.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.
这些计算属性使一个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.m
print("A marathon is \(aMarathon) meters long")
// 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!")
})
// 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.
通过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 = 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:
如果Int值得位数小于索引值,就会返回0,就像在int值的左边添加了0一样:

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:
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, 0, 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语言官方文档翻译(6)-Collection Types

Collection Types

Swift语言官方文档翻译(1)

由于本人准备学swift,但是英语又没达到直接可以阅读的能力,所以就自己先翻译一遍,不用每次都去读英文文档。这就跟当年备考一样,对于阅读理解,不懂的单词都要查出其意思,标注在单词下面,方便以后复习所用...

Swift语言官方文档翻译(4)-Basic Operators

Basic Operators 操作符是一种检查、操作、组合值的特殊的符号或短语。比如将两个值相加(let i = 1 + 2)的加号(+)。更复杂的比如逻辑与(&&)、自增(++i:表示给i加上...

Swift语言官方文档翻译(2)

A Swift Tour

Swift语言官方文档翻译(5)-Strings and Characters

Strings and Characters

Swift 集合类型(Collection Type) 之 set(官方文档翻译及总结)

Swift 集合类型(Collection Type) 之 set(官方文档翻译及总结)
  • soindy
  • soindy
  • 2015-07-15 14:41
  • 1056

Swift 集合类型(Collection Type) 之 数组(array)(官方文档翻译及总结)

Swift 集合类型(Collection Type) 之 数组(array)(官方文档翻译及总结) ‘[NSObject]’ is not convertible to ‘[String]'

Swift语言官方文档翻译(3)-The Basics

The Basics

Swift官方文档翻译

  • 2014-11-20 11:13
  • 12.15MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)