Swift 自加入协议

Swift 自加入协议,swift,Swift,我正在学习swift和玩Xcode。 我总是深入研究定义。我看到: public protocol GeneratorType { typealias Element @warn_unused_result public mutating func next() -> Self.Element? } 符合本协议的结构: public struct IndexingGenerator<Elements : Indexable> : GeneratorTy

我正在学习swift和玩Xcode。 我总是深入研究定义。我看到:

public protocol GeneratorType {
    typealias Element
    @warn_unused_result
    public mutating func next() -> Self.Element?
}
符合本协议的结构:

public struct IndexingGenerator<Elements : Indexable> : GeneratorType, SequenceType {
    public init(_ elements: Elements)
    public mutating func next() -> Elements._Element?
}
公共结构索引生成器:GeneratorType,SequenceType{
公共init(u元素:元素)
公共变异func next()->元素。\u元素?
}
我知道“Self”意味着返回一致类型。但“自我元素”是什么意思? 而实现返回'Elements.'u Element?'的要求的函数,我看不到'Elements.'u Element?'等于'Self.Element?'。 有人能给我解释一下吗?
告诉我更多关于这个。谢谢。

Self.Element
是指任何实现
GeneratorType
协议的类型将声明为其
元素的
类型别名的具体类型

例如,在此斐波那契数生成器中:

struct Fibonacci: GeneratorType {
    typealias Element = Int

    private var value: Int = 1
    private var previous: Int = 0

    mutating func next() -> Element? {
        let newValue = value + previous

        previous = value
        value = newValue

        return previous
    }
}
。。。您实现了
GeneratorType
协议,并指出它的
元素将是什么类型的别名(
Int
,在本例中),而这就是generator的
next()
将返回的类型(实际上是该类型的可选)

但是,在实现参数化协议时,通常不必显式指定typealias,因为Swift足够聪明,可以为您推断它们。例如,对于上述示例中的斐波那契数生成器,也可以执行以下操作:

struct Fibonacci: GeneratorType {
    private var value: Int = 1
    private var previous: Int = 0

    mutating func next() -> Int? {
        let newValue = value + previous

        previous = value
        value = newValue

        return previous
    }
}
。。。Swift从
next()
的签名中知道它返回
Int?
,并且
GeneratorType
实现者的待办事项列表中也必须有
next()
,并且这些方法必须返回
元素?
类型。因此,Swift将2和2放在一起,并推断
元素?
必须与
Int?
相同,因此
元素==Int


关于这一点:

public struct IndexingGenerator<Elements : Indexable> : GeneratorType, SequenceType {
    public init(_ elements: Elements)
    public mutating func next() -> Elements._Element?
}

最后,如果好奇为什么
\u Element
,而不仅仅是
Element
,比如
GeneratorType
,下面是他们在中写的内容(在swift/stdlib/public/core/Collection.swift下):

这里的
\u元素
和下标的声明是用来打破Swift无法处理的循环一致性/推断的技巧。我们需要的不是
CollectionType.Generator.Element
,而是可以用作
IndexingGenerator
元素的
元素。这里我们安排
CollectionType
本身有一个
元素
类型,可以从它的下标中推断出来。理想情况下,我们希望将此
元素
约束为与
CollectionType.Generator.Element
相同,但我们现在无法表达它


我知道,我想知道,返回类型元素。\u元素?和自我元素,我认为你的例子是错误的。应该是这样的,改变func next()->Int?我猜。你的第一个例子是错的。函数应该返回Int?不是元素?请参见编辑。两者都是正确的,区别在于您是显式指定typealias还是允许Swift为您推断类型。我知道的第二个是正确的。但是第一个,如果你显式地告诉编译器,应该显式地告诉它返回值,对吗??
public struct IndexingGenerator<Elements : Indexable> : GeneratorType, SequenceType {
    public typealias Element = Elements._Element
    public init(_ elements: Elements)
    public mutating func next() -> Element?
}