Some Notes on Developing iOS 11 Apps with Swift(2)

本文为大地瓜原创,欢迎知识共享,转载请注明出处。
虽然你不注明出处我也没什么精力和你计较。
作者微信号:christgreenlaw


大地瓜在学习Stanford University的Developing iOS 11 Apps with Swift.
这里记录了一些小笔记。这部分是lecture 4。

这篇文章并不是这个教程的全部内容,只是大地瓜自己学习过程中想记录的一部分内容。


这一节将concentration这个class改为了struct。直接将class关键字改成了struct。

此时有一个func被编译器报错,提示大概意思是,你这个func是immutable的。这个func实际上对concentration的内容进行了修改。我们实际上需要这个func进行修改。所以给这个方法加上了mutating关键字。


protocol

Swift中的protocol就是一系列的功能性声明。这里面没有任何的数据存储。所以谈不上是值类型还是引用类型,它仅仅是个类型而已。

  • Protocols are a way to express an API more concisely
    Instead of forcing the caller of an API to pass a specific class, struct, or enum, an API can let callers pass any class/struct/enum that the caller wants but can require that they implement certain methods and/or properties that the API wants.
    The API expresses the functions or variables it wants the caller to provide using a protocol.
    So a protocol is simply a collection of method and property declarations.
  • What are protocols good for?
    Making API more flexible and expressive
    Blind, structured communication between View and Controller(delegation)
    Mandating behavior(e.g. the keys of a Dictionary must be hashable)
    //这句黑体话在下面有更详细的解释,为什么是强制的行为呢?
    Sharing functionality in disparate types(String, Array, Countable Range are all Collections)
    Multiple inheritance(of functionality, not data)

上方黑体的解释。Swift中的协议,其方法和属性都是mandatory的。强制的。必须要实现。但是OC中有optional方法,你可以实现也可以不实现。Swift为了兼容OC的协议中的optional方法,有一个@objc关键字,加上以后就可以兼容OC的这个特性。
要注意的是,在Swift中基本都是强制的,这种可选的方法实现完全是为了兼容OC。

protocol的三个方面:

  1. protocol declaration(which properties and methods are in the protocol)
  2. a class, struct or enum declaration that makes the claim to implement the protocol
  3. the code in said class, struct or enum(or extensions) that implements the protocol
Some Notes on Developing iOS 11 Apps with Swift(2)_第1张图片
protocol的声明
Some Notes on Developing iOS 11 Apps with Swift(2)_第2张图片
protocol的实现
Some Notes on Developing iOS 11 Apps with Swift(2)_第3张图片
把protocol当做一个类型
用协议实现delegate的详细步骤

在Swift中,closure是一个更好的选择。但代理也挺好的。在iOS中非常常见。

Some Notes on Developing iOS 11 Apps with Swift(2)_第4张图片
一个例子,在iOS开发中常见的代理

你可能感兴趣的:(Some Notes on Developing iOS 11 Apps with Swift(2))