美文网首页
第二十节 Swift 中的协议

第二十节 Swift 中的协议

作者: 码客南君 | 来源:发表于2020-07-15 10:25 被阅读0次

协议定义了用来实现某一特定功能所必需的方法和属性。

协议由类,结构或枚举实现,实现协议要求方法的行为称为遵
守协议。

1.协议的语法

定义协议:

protocol SomeProtocol {
    // protocol definition goes here
}

实现协议:

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // structure definition goes here
}

当一个类有父类,又遵循协议时,要这样写:

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
    // class definition goes here
}

2.协议中的实例属性和类属性

实例属性:

protocol SomeProtocol {
//可读可设置
    var mustBeSettable: Int { get set }
//可读
    var doesNotNeedToBeSettable: Int { get }
}

类属性:

protocol AnotherProtocol {
    static var someTypeProperty: Int { get set }
}

3.协议中的方法

协议中声明的方法没有具体实现,也不能为方法参数指定默认值

protocol SomeProtocol {
    static func someTypeMethod()
}

具体使用:

protocol RandomNumberGenerator {
    func random() -> Double
}

class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m))
        return lastRandom / m
    }
}

let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
// Prints "Here's a random number: 0.3746499199817101"
print("And another one: \(generator.random())")
// Prints "And another one: 0.729023776863283"

相关文章

  • 第二十节 Swift 中的协议

    协议定义了用来实现某一特定功能所必需的方法和属性。 协议由类,结构或枚举实现,实现协议要求方法的行为称为遵守协议。...

  • Swift及SwiftUI学习笔记

    持续更新中...... swift官方文档 swift官方文档(英文) 协议 swift主要基于协议编程的,所以协...

  • Swift 命名空间形式扩展的理解和问题探讨

    先从 Swift 协议扩展的语法说起 注:协议扩展 Protocol extension: Swift 1.x 中...

  • Swift学习笔记-协议

    Swift中的协议类似于Java中的接口,不过在Swift中,结构体,枚举,类都能使用协议 基本用法 符合多个协议...

  • Swift - 协议(protocol)

    Swift - 协议(protocol) 1、Swift中协议类似于别的语言里的接口,协议里只做方法的声明,包括方...

  • 协议(三)

    标准库中的协议 Swift标准库广泛使用的协议可能会让你感到惊讶。理解协议在Swift中扮演的角色可以帮助您编写干...

  • Swift语言总结

    Swift学习总结 协议 协议是方法的集合,它可以把看似不想关的对象的公共行为放到一个协议中。协议在Swift开发...

  • 【Tips】Swift Protocol

    前言 本文是笔者学习Swift协议的笔记。 开始 OC中判断是否遵守某个协议有对应的方法,Swift中也有,但是开...

  • swift方法参数遵守多继承和遵守多个协议

    参数继承协议 OC中 id Swift 3 protocol Swift 4 A & B 文档

  • OC和Swift比较

    OC与swift 1.协议 OC:主要用来传值 swift:不仅可以用来传值,swift中的协议可以定义属性方法,...

网友评论

      本文标题:第二十节 Swift 中的协议

      本文链接:https://www.haomeiwen.com/subject/bwhdhktx.html