深入解析Swift语言中的协议

 更新时间:2015年11月08日 16:32:42   投稿:goldensun  
这篇文章主要介绍了深入解析Swift语言中的协议,是Swift入门学习中的基础知识,需要的朋友可以参考下

协议为方法,属性和其他要求的功能提供了一个蓝本。它只是描述了方法或属性的骨架,而不是实现。方法和属性实现还可以通过定义类,函数和枚举完成。协议的一致性是指方法或属性满足协议的要求。

语法
协议也遵循类似类,结构和枚举的语法:

复制代码 代码如下:

protocol SomeProtocol {
    // protocol definition
}

协议在类,结构或枚举类型命名声明。单个和多个协议的声明也是可以的。如果多个协议规定,它们必须用逗号分隔。
复制代码 代码如下:

struct SomeStructure: Protocol1, Protocol2 {
    // structure definition
}

当一个协议在超类中定义,协议名称应遵循命名在超类之后。
复制代码 代码如下:

class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
    // class definition
}

属性和方法的要求
协议用于指定特定类型的属性或属性的实例。它仅指定类型或实例属性单独而不是指定它是否是一个存储或计算属性。另外,它是用来指定的属性是否为“可获取'或'可设置”。

属性要求由 “var” 关键字作为属性变量声明。 {get set} 使用它们类型声明后声明属性可获取和可设置。 可获取是由它们的类型{get}取属性声明后提及。

复制代码 代码如下:

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

不同变形方法要求

复制代码 代码如下:

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

初始化程序要求
Swift 允许用户初始化协议遵循类似于正常初始化类型的一致性。

语法

复制代码 代码如下:

protocol SomeProtocol {
   init(someParameter: Int)
}

示例
复制代码 代码如下:

protocol tcpprotocol {
   init(aprot: Int)
}

协议初始化程序要求类实现
指定或初始化便捷允许用户初始化协议来预留“required”关键字,以符合其标准。
复制代码 代码如下:

class SomeClass: SomeProtocol {
   required init(someParameter: Int) {
      // initializer implementation statements
   }
}

protocol tcpprotocol {
   init(aprot: Int)
}

class tcpClass: tcpprotocol {
   required init(aprot: Int) {
   }
}


协议一致性保证所有子类显式或继承实现“required”修辞符。

当一个子类覆盖其超类的初始化必须由“override”修饰符关键字指定。

复制代码 代码如下:

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

协议作为类型
相反,在协议执行的功能被用作函数,类,方法等类型。

协议可以访问作为类型:

函数,方法或初始化作为一个参数或返回类型

常量,变量或属性

数组,字典或其他容器作为项目

复制代码 代码如下:

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]

添加协议一致性与扩展
已有的类型可以通过和利用扩展符合新的协议。新属性,方法和下标可以被添加到现有的类型在扩展的帮助下。

复制代码 代码如下:

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"
      }
   }
}


协议继承
Swift 允许协议继承其定义的属性的属性。它类似于类的继承,但用逗号分隔列举选择多个继承协议。
复制代码 代码如下:

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

只有类协议
当协议被定义,并且用户想要定义协议与它应该通过定义类第一后跟协议的继承列表被添加的类。

复制代码 代码如下:

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

协议组合
Swift 允许多个协议在协议组合的帮助下调用一次。

语法

复制代码 代码如下:

protocol<SomeProtocol, AnotherProtocol>

示例
复制代码 代码如下:

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

检查协议一致性
协议一致性是 is 和 as 类似于类型转换的操作符测试。

如果一个实例符合协议标准,is运算符如果失败返回false ,否则返回true。

as? 版本是向下转型操作符,返回协议的类型的可选值,并且如果该值是nil ,实例不符合该协议。

as 版是向下转型操作符,强制向下转型的协议类型并触发一个运行时错误,如果向下转型不会成功。

复制代码 代码如下:

 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

您可能感兴趣的文章:

相关文章

  • Swift能代替Objective-C吗?

    Swift能代替Objective-C吗?

    这是我在网上上看到的答案,复制粘贴过来和大家分享一下,因为我和很多人一样很关心Swift的出现对Mac开发的影响和对Objective-C的影响。
    2014-09-09
  • switch多选择结构、循环结构示例详解

    switch多选择结构、循环结构示例详解

    这篇文章主要介绍了switch多选择结构、循环结构,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-12-12
  • Swift实现简单计算器项目

    Swift实现简单计算器项目

    这篇文章主要为大家详细介绍了Swift实现简单计算器项目,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • Swift使用SnapKit模仿Kingfisher第三方扩展优化

    Swift使用SnapKit模仿Kingfisher第三方扩展优化

    这篇文章主要为大家介绍了Swift SnapKit模仿Kingfisher第三方扩展优化示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • Swift中swift中的switch 语句

    Swift中swift中的switch 语句

    本文给大家介绍了swift中的swift语句,以及和c语音中的写法区别,本文介绍的非常详细,需要的朋友参考下
    2016-12-12
  • Swift开发之UITableView状态切换效果

    Swift开发之UITableView状态切换效果

    这篇文章主要介绍了Swift开发之UITableView状态切换效果的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-08-08
  • Swift中初始化方法的顺序介绍

    Swift中初始化方法的顺序介绍

    这篇文章主要介绍了Swift中初始化方法的顺序介绍,本文介绍的是了类的初始化方法,需要的朋友可以参考下
    2015-01-01
  • 详解Swift 结构体

    详解Swift 结构体

    这篇文章主要介绍了Swift 结构体的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-09-09
  • 深入理解Swift中的变量与常量

    深入理解Swift中的变量与常量

    本文主要是介绍Swift中最常用的常量和变量,将从“变量常量的定义”、"如何声明变量常量"、“变量和常量的命名”,"变量常量的本质区别"四个方面入手,重点介绍变量和常量的使用以及区别,希望大家在阅读完本文后都可以熟练使用它们。有需要的朋友们下面来一起学习吧。
    2017-01-01
  • iOS Swift UICollectionView横向分页滚动,cell左右排版问题详解

    iOS Swift UICollectionView横向分页滚动,cell左右排版问题详解

    UICollectionView是iOS中比较常见的一个控件,这篇文章主要给大家介绍了关于iOS Swift UICollectionView横向分页滚动,cell左右排版问题的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随小编来一起学习学习吧。
    2017-12-12

最新评论