源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

深入解析Swift语言中的协议

  • 时间:2022-12-10 08:45 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:深入解析Swift语言中的协议
协议为方法,属性和其他要求的功能提供了一个蓝本。它只是描述了方法或属性的骨架,而不是实现。方法和属性实现还可以通过定义类,函数和枚举完成。协议的一致性是指方法或属性满足协议的要求。 [b]语法 [/b]协议也遵循类似类,结构和枚举的语法:
[u]复制代码[/u] 代码如下:
protocol SomeProtocol {     // protocol definition }
协议在类,结构或枚举类型命名声明。单个和多个协议的声明也是可以的。如果多个协议规定,它们必须用逗号分隔。
[u]复制代码[/u] 代码如下:
struct SomeStructure: Protocol1, Protocol2 {     // structure definition }
当一个协议在超类中定义,协议名称应遵循命名在超类之后。
[u]复制代码[/u] 代码如下:
class SomeClass: SomeSuperclass, Protocol1, Protocol2 {     // class definition }
[b]属性和方法的要求 [/b]协议用于指定特定类型的属性或属性的实例。它仅指定类型或实例属性单独而不是指定它是否是一个存储或计算属性。另外,它是用来指定的属性是否为“可获取'或'可设置”。 属性要求由 “var” 关键字作为属性变量声明。 {get set} 使用它们类型声明后声明属性可获取和可设置。 可获取是由它们的类型{get}取属性声明后提及。
[u]复制代码[/u] 代码如下:
protocol classa {       var marks: Int { get set }    var result: Bool { get }       func attendance() -> String    func markssecured() -> String    } protocol classb: classa {       var present: Bool { get set }    var subject: String { get set }    var stname: String { get set }    } class classc: classb {    var marks = 96    let result = true    var present = false    var subject = "Swift Protocols"    var stname = "Protocols"       func attendance() -> String {       return "The \(stname) has secured 99% attendance"    }       func markssecured() -> String {       return "\(stname) has scored \(marks)"    } } let studdet = classc() studdet.stname = "Swift" studdet.marks = 98 studdet.markssecured() println(studdet.marks) println(studdet.result) println(studdet.present) println(studdet.subject) println(studdet.stname)
当我们使用 playground 运行上面的程序,得到以下结果。
98
true
false
Swift Protocols
Swift
[b]不同变形方法要求 [/b]
[u]复制代码[/u] 代码如下:
protocol daysofaweek {    mutating func print() } enum days: daysofaweek {    case sun, mon, tue, wed, thurs, fri, sat    mutating func print() {       switch self {       case sun:          self = sun          println("Sunday")       case mon:          self = mon          println("Monday")       case tue:          self = tue          println("Tuesday")       case wed:          self = wed          println("Wednesday")       case mon:          self = thurs          println("Thursday")       case tue:          self = fri          println("Friday")       case sat:          self = sat          println("Saturday")       default:          println("NO Such Day")       }    } } var res = days.wed res.print()
当我们使用 playground 运行上面的程序,得到以下结果。
Wednesday
[b]初始化程序要求 [/b]Swift 允许用户初始化协议遵循类似于正常初始化类型的一致性。 语法
[u]复制代码[/u] 代码如下:
protocol SomeProtocol {    init(someParameter: Int) }
示例
[u]复制代码[/u] 代码如下:
protocol tcpprotocol {    init(aprot: Int) }
协议初始化程序要求类实现 指定或初始化便捷允许用户初始化协议来预留“required”关键字,以符合其标准。
[u]复制代码[/u] 代码如下:
class SomeClass: SomeProtocol {    required init(someParameter: Int) {       // initializer implementation statements    } } protocol tcpprotocol {    init(aprot: Int) } class tcpClass: tcpprotocol {    required init(aprot: Int) {    } }
协议一致性保证所有子类显式或继承实现“required”修辞符。 当一个子类覆盖其超类的初始化必须由“override”修饰符关键字指定。
[u]复制代码[/u] 代码如下:
protocol tcpprotocol {    init(no1: Int) } class mainClass {    var no1: Int // local storage    init(no1: Int) {       self.no1 = no1 // initialization    } } class subClass: mainClass, tcpprotocol {    var no2: Int    init(no1: Int, no2 : Int) {       self.no2 = no2       super.init(no1:no1)    }    // Requires only one parameter for convenient method    required override convenience init(no1: Int)  {       self.init(no1:no1, no2:0)    } } let res = mainClass(no1: 20) let print = subClass(no1: 30, no2: 50) println("res is: \(res.no1)") println("res is: \(print.no1)") println("res is: \(print.no2)")
当我们使用 playground 运行上面的程序,得到以下结果。
res is: 20
res is: 30
res is: 50
[b]协议作为类型 [/b]相反,在协议执行的功能被用作函数,类,方法等类型。 协议可以访问作为类型: 函数,方法或初始化作为一个参数或返回类型 常量,变量或属性 数组,字典或其他容器作为项目
[u]复制代码[/u] 代码如下:
protocol Generator {    typealias members    func next() -> members? } var items = [10,20,30].generate() while let x = items.next() {    println(x) } for lists in map([1,2,3], {i in i*5}) {    println(lists) } println([100,200,300]) println(map([1,2,3], {i in i*10}))
当我们使用 playground 运行上面的程序,得到以下结果。
10
20
30
5
10
15
[100, 200, 300]
[10, 20, 30]
[b]添加协议一致性与扩展 [/b]已有的类型可以通过和利用扩展符合新的协议。新属性,方法和下标可以被添加到现有的类型在扩展的帮助下。
[u]复制代码[/u] 代码如下:
protocol AgeClasificationProtocol {    var age: Int { get }    func agetype() -> String } class Person {    let firstname: String    let lastname: String    var age: Int    init(firstname: String, lastname: String) {       self.firstname = firstname       self.lastname = lastname       self.age = 10    } } extension Person : AgeClasificationProtocol {    func fullname() -> String {       var c: String       c = firstname + " " + lastname       return c    }       func agetype() -> String {       switch age {       case 0...2:          return "Baby"       case 2...12:          return "Child"       case 13...19:          return "Teenager"       case let x where x > 65:          return "Elderly"       default:          return "Normal"       }    } }
[b]协议继承 [/b]Swift 允许协议继承其定义的属性的属性。它类似于类的继承,但用逗号分隔列举选择多个继承协议。
[u]复制代码[/u] 代码如下:
protocol classa {    var no1: Int { get set }    func calc(sum: Int) } protocol result {    func print(target: classa) } class student2: result {    func print(target: classa) {       target.calc(1)    } } class classb: result {    func print(target: classa) {       target.calc(5)    } } class student: classa {    var no1: Int = 10       func calc(sum: Int) {       no1 -= sum       println("Student attempted \(sum) times to pass")             if no1 <= 0 {          println("Student is absent for exam")       }    } } class Player {    var stmark: result!       init(stmark: result) {       self.stmark = stmark    }       func print(target: classa) {       stmark.print(target)    } } var marks = Player(stmark: student2()) var marksec = student() marks.print(marksec) marks.print(marksec) marks.print(marksec) marks.stmark = classb() marks.print(marksec) marks.print(marksec) marks.print(marksec)
当我们使用 playground 运行上面的程序,得到以下结果。
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 5 times to pass
Student attempted 5 times to pass
Student is absent for exam
Student attempted 5 times to pass
Student is absent for exam
[b]只有类协议 [/b]当协议被定义,并且用户想要定义协议与它应该通过定义类第一后跟协议的继承列表被添加的类。
[u]复制代码[/u] 代码如下:
protocol tcpprotocol {    init(no1: Int) } class mainClass {    var no1: Int // local storage    init(no1: Int) {       self.no1 = no1 // initialization    } } class subClass: mainClass, tcpprotocol {    var no2: Int    init(no1: Int, no2 : Int) {       self.no2 = no2       super.init(no1:no1)    }    // Requires only one parameter for convenient method    required override convenience init(no1: Int)  {       self.init(no1:no1, no2:0)    } } let res = mainClass(no1: 20) let print = subClass(no1: 30, no2: 50) println("res is: \(res.no1)") println("res is: \(print.no1)") println("res is: \(print.no2)")
当我们使用 playground 运行上面的程序,得到以下结果。
res is: 20
res is: 30
res is: 50
[b]协议组合 [/b]Swift 允许多个协议在协议组合的帮助下调用一次。 语法
[u]复制代码[/u] 代码如下:
protocol<SomeProtocol, AnotherProtocol>
示例
[u]复制代码[/u] 代码如下:
protocol stname {    var name: String { get } } protocol stage {    var age: Int { get } } struct Person: stname, stage {    var name: String    var age: Int } func print(celebrator: protocol<stname, stage>) {    println("\(celebrator.name) is \(celebrator.age) years old") } let studname = Person(name: "Priya", age: 21) print(studname) let stud = Person(name: "Rehan", age: 29) print(stud) let student = Person(name: "Roshan", age: 19) print(student)
当我们使用 playground 运行上面的程序,得到以下结果。
Priya is 21 years old
Rehan is 29 years old
Roshan is 19 years old
[b]检查协议一致性 [/b]协议一致性是 is 和 as 类似于类型转换的操作符测试。 如果一个实例符合协议标准,is运算符如果失败返回false ,否则返回true。 as? 版本是向下转型操作符,返回协议的类型的可选值,并且如果该值是nil ,实例不符合该协议。 as 版是向下转型操作符,强制向下转型的协议类型并触发一个运行时错误,如果向下转型不会成功。
[u]复制代码[/u] 代码如下:
 import Foundation @objc protocol rectangle {    var area: Double { get } } @objc class Circle: rectangle {    let pi = 3.1415927    var radius: Double    var area: Double { return pi * radius * radius }    init(radius: Double) { self.radius = radius } } @objc class result: rectangle {    var area: Double    init(area: Double) { self.area = area } } class sides {    var rectsides: Int    init(rectsides: Int) { self.rectsides = rectsides } } let objects: [AnyObject] = [Circle(radius: 2.0),result(area: 198),sides(rectsides: 4)] for object in objects {    if let objectWithArea = object as? rectangle {       println("Area is \(objectWithArea.area)")    } else {       println("Rectangle area is not defined")    } }
当我们使用 playground 运行上面的程序,得到以下结果。
Area is 12.5663708
Area is 198.0
Rectangle area is not defined

  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部