swift扩展
Continuing with our series of Swift tutorials, we’ll be discussing and playing around with Swift Extension in this tutorial.
继续我们的Swift教程系列,我们将在本教程中讨论和使用Swift Extension。
Swift Extension is a useful feature that helps in adding more functionality to an existing Class, Structure, Enumeration or a Protocol type. This includes adding functionalities for types where you don’t have the original source code too (extensions for Int, Bool etc. types).
Swift扩展是一项有用的功能,有助于为现有的Class , Structure , Enumeration或Protocol类型添加更多功能。 这包括为您也没有原始源代码的类型(Int,Bool等类型的扩展名)添加功能。
Following are the essential functionalities that Swift Extension offer us:
以下是Swift Extension为我们提供的基本功能:
Note: Stored Properties can’t be added to Extensions. Swift Extensions don’t support overriding properties and method implementations.
注意 :无法将存储的属性添加到扩展。 Swift扩展不支持重写属性和方法实现。
Following is the syntax used for creating swift extension.
以下是用于创建快速扩展的语法。
extension ClassStructEnumOrProtocolNameGoesHere {
//add functionality to the above type
}
Let’s open our Xcode playground and start working with Extensions.
让我们打开Xcode游乐场并开始使用Extensions。
extension Int {
var square : Int{
return self*self
}
func cube()->Int{
return self*self*self
}
mutating func incrementBy5() {
self = self + 5
}
}
var x : Int = 5
print(x.square) //prints "25\n"
print(x.cube()) //prints "125\n"
x.incrementBy5() // 10
In the above code, we’ve created a read-only computed property to calculate the square of the number. Hence get is omitted.
在上面的代码中,我们创建了一个只读的计算属性以计算数字的平方。 因此,省略了get。
To modify the value of the type itself, a mutating Function is used.
为了修改类型本身的值,使用了一个变异函数 。
extension String {
var length: Int {
get {
return self.characters.count
}
}
mutating func addString(str: String) {
self = self + str
}
}
var stringA = "Hello"
stringA.length // 5
stringA.addString(str: "World") //HelloWorld
stringA.length // 10
Note: A designated initializer is the primary initializer for a class. It must fully initialize all properties introduced by its class. A class can have more than one designated initializer.
注意 :指定的初始化器是类的主要初始化器。 它必须完全初始化其类引入的所有属性。 一个类可以具有多个指定的初始化程序。
An example implementation with class is given below.
下面给出了带有类的示例实现。
class A {
var name : String
var age : Int
init(name: String, age: Int) {
self.age = age
self.name = name
}
}
extension A {
convenience init() {
self.init(name: "No name yet", age: 0)
}
}
var a = A()
print(a.name) //prints "No name yet"
print(a.age) //prints 0
We know that structs create the default initialisers with all the properties for us as shown below:
我们知道结构会为我们创建所有属性的默认初始化器,如下所示:
struct S {
var name : String
var age : Int
}
var s = S(name: "Anupam", age: 23)
Once we define our own initializer, Swift forbids us from using the above default initialiser:
一旦定义了自己的初始化程序,Swift就会禁止我们使用上述默认初始化程序:
struct S {
var name : String
var age : Int
init(age : Int) {
self.age = age
self.name = "A boy has no name"
}
}
var s = S(age: 16)
s.name //A boy has no name
s.age //16
Using the power of Extensions we can preserve the default initalisers too that structs provide as shown below.
使用扩展功能,我们还可以保留结构提供的默认初始化器,如下所示。
struct S {
var name : String
var age : Int
}
extension S {
init(age : Int) {
self.age = age
self.name = "A boy has no name"
}
}
var s = S(age: 16)
var s1 = S(name: "Anupam", age: 23)
Swift Extensions can add new subscripts to an existing type as shown below.
Swift扩展可以将新的下标添加到现有类型,如下所示。
extension String {
var length: Int {
return self.characters.count
}
subscript (i: Int) -> String {
return self[i ..< i + 1]
}
subscript (r: Range) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
}
var sa : String = "hello"
sa[2] // l
sa[0..<4] // hell
Awesome! We’ve created an extension for a string through which we can access a character or a range of characters just like an Array.
太棒了! 我们已经为字符串创建了扩展名,通过它我们可以访问一个字符或一系列字符,就像数组一样。
We’ve adopted TableView protocols. There’s an alternative though. We can write an extension and conform the protocols to it thereby making the code organized and structured better than before as shown below.
我们采用了TableView协议。 不过,还有另一种选择。 我们可以编写一个扩展并使其符合协议,从而使代码的组织和结构比以前更好,如下所示。
//Earlier approach.
class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
//All the functions of both the protocols must be implemented here.
}
//Newer and Better Approach
class ViewController : UIViewController {
//Keep class specific code here
}
extension ViewController : UITableViewDataSource {
//Implement the methods of DataSource protocol only.
}
extension ViewController : UITableViewDelegate{
//Implement the methods of Delegate protocol only.
}
Navigating through the code structure becomes much easier when protocols are adopted in extensions.
当扩展中采用协议时,浏览代码结构变得更加容易。
class C : Name
{
var name: String
init(name: String) {
self.name = name
}
}
extension C : Greet {
func greet() -> String{
return "Hello, \(name)"
}
}
var c = C(name: "Anupam")
c.greet() //prints "Hello, Anupam"
Extensions can be useful for creating nested types of classes, structures or enumerations.
Let’s explain this by an example.
扩展对于创建嵌套类型的类,结构或枚举很有用。
让我们通过一个例子来解释一下。
extension String{
var length: Int {
get {
return self.characters.count
}
}
enum Length{
case Zero, NotZero
}
var isZero : Length{
switch self.length{
case 0 : return .Zero
default : return .NotZero
}
}
}
func checkLength(s: String){
switch s.isZero {
case .Zero:
print("The length of your string is zero")
case .NotZero:
print("The length of your string is NOT zero")
}
}
var myString = ""
checkLength(s: myString) //prints "The length of your string is zero\n"
myString = "Hi"
checkLength(s: myString) //prints "The length of your string is NOT zero\n"
We’ve able to group strings based on their length using enums inside an Extension.
我们已经可以使用扩展中的枚举根据字符串的长度对字符串进行分组。
This brings an end to swift extension tutorial. Extensions, when used correctly can be very handy in your Swift Programming.
这样就结束了快速扩展教程。 如果正确使用扩展,在您的Swift编程中会非常方便。
References : Apple Docs
参考文献: Apple Docs
swift扩展