组合类型别名的协议和空一致协议之间的区别

Mar*_*tin 5 swift swift-protocols

Swift 中这两者有区别吗?

  • protocol ABProtocol: AProtocol, BProtocol {}
  • typealias ABProtocol = AProtocol&BProtocol

Jer*_*myP 2

是,有一点不同。前者定义了一个新的协议,使用该协议时类型必须遵守该协议。后者仅定义了一个“占位符”AProtocol&BProtocol

考虑以下代码:

protocol AProtocol{}
protocol BProtocol{}

protocol ABProtocol1: AProtocol, BProtocol {}
typealias ABProtocol2 = AProtocol & BProtocol

func f1(value: ABProtocol1) {}
func f2(value: ABProtocol2) {}
Run Code Online (Sandbox Code Playgroud)

的参数f1必须符合,ABProtocol1但参数f2可以符合AProtocolBProtocol。您不需要显式地使类型符合ABProtocol2. 例如:

struct A: AProtocol, BProtocol
{
}

f1(value: A()) // Error!
f2(value: A()) // OK
Run Code Online (Sandbox Code Playgroud)