Latest web development tutorials

Swift agreement

Agreement to implement the methods and properties required for a particular function.

Able to meet the requirements of any type of agreement is known as follow (conform) the agreement.

Class, structure, or enumeration types can follow protocols and provides specific implementation to complete the protocol-defined methods and functions.

grammar

Syntax agreement are as follows:

protocol SomeProtocol {
    // 协议内容
}

To follow a protocol class, you need to type in the name with the protocol name, middle colon: separated, as part of the type definition. When multiple protocols to follow, with a comma between each protocol separated.

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // 结构体内容
}

If the class has to follow the protocol while parent, the parent class name should be placed before the protocol name, separated by commas.

class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
    // 类的内容
}

Provision of property

Protocol is used to specify a particular instance of the class attribute or property, without specifying the type attribute memory or computational property. It must also be indicated as read-only or read-write.

Agreement is usually to declare variables var attribute type declaration after adding {set get} to represent the property is readable and writable, read-only attribute is represented by {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 协议"
    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()

print(studdet.marks)
print(studdet.result)
print(studdet.present)
print(studdet.subject)
print(studdet.stname)

The above program execution output is:

98
true
false
Swift 协议
Swift

Methods of Mutating provisions

Sometimes you need to change it in an instance method.

For example, the value type (struct, enum) instance method, the mutating keyword as a prefix function, written before func, showing a modified example of the value of its instances can attribute it belongs in the process.

protocol daysofaweek {
    mutating func show()
}

enum days: daysofaweek {
    case sun, mon, tue, wed, thurs, fri, sat
    mutating func show() {
        switch self {
        case sun:
            self = sun
            print("Sunday")
        case mon:
            self = mon
            print("Monday")
        case tue:
            self = tue
            print("Tuesday")
        case wed:
            self = wed
            print("Wednesday")
        case mon:
            self = thurs
            print("Thursday")
        case tue:
            self = fri
            print("Friday")
        case sat:
            self = sat
            print("Saturday")
        default:
            print("NO Such Day")
        }
    }
}

var res = days.wed
res.show()

The above program execution output is:

Wednesday

The provisions of the constructor

Agreement may require it to follow those who implement the specified constructor.

You can write like an ordinary constructor, as constructors wrote a statement in the definition in the agreement, but do not write braces and constructors entity syntax is as follows:

protocol SomeProtocol {
   init(someParameter: Int)
}

Examples

protocol tcpprotocol {
   init(aprot: Int)
}

Protocol specified in the class constructor implementation

You can follow the agreement constructor in class, and specify whether it is convenient to specify the constructor or class constructor. In both cases, you have to be to achieve the constructor superscript "required" modifier:

class SomeClass: SomeProtocol {
   required init(someParameter: Int) {
      // 构造器实现
   }
}

protocol tcpprotocol {
   init(aprot: Int)
}

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

Use modifier guarantees required: follow all subclasses of the agreement, it can also provide an explicit implementation or inherit the constructor to fulfilling.

If a subclass overrides the specified parent class constructor, and the constructor follows the provisions of an agreement, then the constructor implementation needs to be marked simultaneously required and override modifiers:

protocol tcpprotocol {
    init(no1: Int)
}

class mainClass {
    var no1: Int // 局部变量
    init(no1: Int) {
        self.no1 = no1 // 初始化
    }
}

class subClass: mainClass, tcpprotocol {
    var no2: Int
    init(no1: Int, no2 : Int) {
        self.no2 = no2
        super.init(no1:no1)
    }
    // 因为遵循协议,需要加上"required"; 因为继承自父类,需要加上"override"
    required override convenience init(no1: Int)  {
        self.init(no1:no1, no2:0)
    }
}
let res = mainClass(no1: 20)
let show = subClass(no1: 30, no2: 50)

print("res is: \(res.no1)")
print("res is: \(show.no1)")
print("res is: \(show.no2)")

The above program execution output is:

res is: 20
res is: 30
res is: 50

agreement type

Although the agreement itself does not implement any function, but can be used as the protocol type to use.

Like other protocols may use the same general type, usage scenarios:

  • As a function, method, or constructor parameter types or return value type
  • As a type of constants, variables, or properties
  • As an array, a dictionary or other container element type

Examples

protocol Generator {
    typealias members
    func next() -> members?
}

var items = [10,20,30].generate()
while let x = items.next() {
    print(x)
}

for lists in [1,2,3].map( {i in i*5}) {
    print(lists)
}

print([100,200,300])
print([1,2,3].map({i in i*10}))

The above program execution output is:

10
20
30
5
10
15
[100, 200, 300]
[10, 20, 30]

Adding members in the extension agreement

We can extend to expand the types (classes, structures, enumerations, etc.) already exists.

Extensions can add member properties, methods, and index the script, as the protocol type that already exists.

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

Inheritance agreement

Protocol can inherit one or more other protocols, you can add new content requires agreement on the basis of inheritance.

The syntax is similar to inheritance and class inheritance protocol, separated by a comma between multiple inherited Agreement:

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
    // 协议定义
}

Examples

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
        print("学生尝试 \(sum) 次通过")
        
        if no1 <= 0 {
            print("学生缺席考试")
        }
    }
}

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)

The above program execution output is:

学生尝试 1 次通过
学生尝试 1 次通过
学生尝试 1 次通过
学生尝试 5 次通过
学生尝试 5 次通过
学生缺席考试
学生尝试 5 次通过
学生缺席考试

Exclusive Agreement

You can inherit a list of protocol, by adding the class keyword restraint agreements can only fit into the category (class) type.

The class must be the first keyword appears in the list of protocols in succession, then, is the other successor agreement. Format is as follows:

protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol {
    // 协议定义
}

Examples

protocol TcpProtocol {
    init(no1: Int)
}

class MainClass {
    var no1: Int // 局部变量
    init(no1: Int) {
        self.no1 = no1 // 初始化
    }
}

class SubClass: MainClass, TcpProtocol {
    var no2: Int
    init(no1: Int, no2 : Int) {
        self.no2 = no2
        super.init(no1:no1)
    }
    // 因为遵循协议,需要加上"required"; 因为继承自父类,需要加上"override"
    required override convenience init(no1: Int)  {
        self.init(no1:no1, no2:0)
    }
}

let res = MainClass(no1: 20)
let show = SubClass(no1: 30, no2: 50)

print("res is: \(res.no1)")
print("res is: \(show.no1)")
print("res is: \(show.no2)")

The above program execution output is:

res is: 20
res is: 30
res is: 50

Synthesis Protocol

Swift synthesis support multiple protocols, which is very useful when we need to follow more than one protocol.

Syntax is as follows:

protocol<SomeProtocol, AnotherProtocol>

Examples

protocol Stname {
    var name: String { get }
}

protocol Stage {
    var age: Int { get }
}

struct Person: Stname, Stage {
    var name: String
    var age: Int
}

func show(celebrator: protocol<Stname, Stage>) {
    print("\(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)

The above program execution output is:

Person(name: "Priya", age: 21)
Person(name: "Rehan", age: 29)
Person(name: "Roshan", age: 19)

Consistency Inspection Agreement

You can use the is and as operators to check compliance with a protocol or forced into a certain type.

  • is operator to check whether an instance 遵循 a certain 协议 .
  • as? returns an optional value, when the instance is 遵循 when the agreement to return the protocol type; otherwise it returns nil .
  • as for mandatory downcast, fails if the strong turn, will cause a runtime error.

Examples

The following example defines a HasArea protocol requires a Double type readable area:

protocol HasArea {
    var area: Double { get }
}

// 定义了Circle类,都遵循了HasArea协议
class Circle: HasArea {
    let pi = 3.1415927
    var radius: Double
    var area: Double { return pi * radius * radius }
    init(radius: Double) { self.radius = radius }
}

// 定义了Country类,都遵循了HasArea协议
class Country: HasArea {
    var area: Double
    init(area: Double) { self.area = area }
}

// Animal是一个没有实现HasArea协议的类
class Animal {
    var legs: Int
    init(legs: Int) { self.legs = legs }
}

let objects: [AnyObject] = [
    Circle(radius: 2.0),
    Country(area: 243_610),
    Animal(legs: 4)
]

for object in objects {
    // 对迭代出的每一个元素进行检查,看它是否遵循了HasArea协议
    if let objectWithArea = object as? HasArea {
        print("面积为 \(objectWithArea.area)")
    } else {
        print("没有面积")
    }
}

The above program execution output is:

面积为 12.5663708
面积为 243610.0
没有面积