swift扩展_Swift扩展

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扩展 (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扩展是一项有用的功能,有助于为现有的ClassStructureEnumeration或Protocol类型添加更多功能。 这包括为您也没有原始源代码的类型(Int,Bool等类型的扩展名)添加功能。

Following are the essential functionalities that Swift Extension offer us:

以下是Swift Extension为我们提供的基本功能:

  1. Add computed instance 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

    使现有类型符合协议

Note: Stored Properties can’t be added to Extensions. Swift Extensions don’t support overriding properties and method implementations.

注意 :无法将存储的属性添加到扩展。 Swift扩展不支持重写属性和方法实现。

Swift扩展语法 (Swift Extension Syntax)

Following is the syntax used for creating swift extension.

以下是用于创建快速扩展的语法。

extension ClassStructEnumOrProtocolNameGoesHere {
    //add functionality to the above type
}

Swift类扩展示例 (Swift Class Extension Example)

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

在Swift扩展中实现初始化程序 (Implementing Initialisers in Swift Extensions)

  • Swift Extensions can add new initialisers to existing types.

    Swift Extensions可以向现有类型添加新的初始化程序。
  • Extensions for classes can add new convenience initialisers. Designated Initialisers for classes must be present in the class implementation only.

    类的扩展可以添加新的便利初始化器。 类的指定初始化程序只能存在于类实现中。
  • Deinitialisers aren’t possible in extensions.

    扩展程序中无法使用反初始化程序。

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扩展下标 (Swift Extension Subscripts)

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.

太棒了! 我们已经为字符串创建了扩展名,通过它我们可以访问一个字符或一系列字符,就像数组一样。

Swift协议扩展 (Swift Protocol Extension)

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"

使用Swift扩展的嵌套类型 (Nested Types using Swift Extension)

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

翻译自: https://www.journaldev.com/16882/swift-extension

swift扩展

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值