微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift的关联类型 草稿

swift的关联类型

 

带有关联类型的protocol

具有类型模版和构造双重功能

 

泛型与普通类型的结合:类型构造器

泛型与抽象类型的结合:高阶抽象模版。

 

阶段的不同:

构造阶段     vs     定义阶段

 

associatedtype是protocol与泛型结合的产物

泛型类型是类型构造器,用于生成新的类型;然后用来定义变量;

协议是模版类,只能用于定义类型;不能作为类型构造器来使用;

 

不完备构造类型:泛型构造器;抽象构造类型;

抽象类型:抽象模版类型

 

Associated Types

When defining a protocol, it’s sometimes useful to declare one or more associated types as part of the protocol’s deFinition. An associated type gives a placeholder name to a type that is used as part of the protocol. The actual type to use for that associated type isn’t specified until the protocol is adopted. Associated types are specified with the associatedtype keyword.

 

https://docs.swift.org/swift-book/LanguageGuide/Generics.html

 

 

1、赋值方式:

显式赋值

类型推断赋值

 

2、关联类型在协议内的作用:

成员变量

函数参量

返回值

 

3、关联类型的组织作用

一个类型与另一个类型产生联系;

 

swift协议的分类

 

接口类型:无关联类型和无Self作为参量的协议;

可以作为参量类型和变量类型:

Protocols as Types

Protocols don’t actually implement any functionality themselves. Nonetheless, any protocol you create will become a fully-fledged type for use in your code.

Because it’s a type, you can use a protocol in many places where other types are allowed, including:

  • As a parameter type or return type in a function, method, or initializer
  • As the type of a constant, variable, or property
  • As the type of items in an array, dictionary, or other container

 

 

抽象类型(不完备类型):

在变量声明中只能作为类型修饰符存在。

 

泛型与关联类型

 

public protocol Sequence {

    associatedtype Iterator : IteratorProtocol

    

    public func makeIterator() -> Self.Iterator

    

    // ...

}

 

// MARK: non-optional properties

public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: Transform) -> CustomMappingkeyvalueTuple {

    return property <-- (nil, transformer)

}

 

 

protocol NoSelfProtocol {}

 

Protocol 'Sequencible' can only be used as a generic constraint because it has Self or associated type requirements

 

协议作为约束

public protocol Sequence {

    associatedtype Iterator : IteratorProtocol

    

    public func makeIterator() -> Self.Iterator

    

    // ...

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐