2015-06-21 3 views
0

Я не понимаю тип возврата для array.indexOf() в swift. Когда я приказываю нажмите функцию, которую он принимает меня расширение для протокола:Быстрые протоколы и расширения протоколов с CollectionType

extension CollectionType where Generator.Element : Equatable { 

/// Returns the first index where `value` appears in `self` or `nil` if 
/// `value` is not found. 
/// 
/// - Complexity: O(`self.count`). 
func indexOf(element: Self.Generator.Element) -> Self.Index? 
} 

Метод IndexOf возвращает Self.Index ?,

, как он знает, что его в Int?

+0

Array.startIndex возвращает Int. таким образом, Self.Index будет выведено на int –

ответ

2

Если вы заглянете в Swift заголовок для _CollectionDefaultsType, вы увидите определение протокола следующим образом,

protocol _CollectionDefaultsType : SequenceType { 

    /// A type that represents a valid position in the collection. 
    /// 
    /// Valid indices consist of the position of every element and a 
    /// "past the end" position that's not valid for use as a subscript. 
    typealias Index : ForwardIndexType 

    /// The position of the first element in a non-empty collection. 
    /// 
    /// In an empty collection, `startIndex == endIndex`. 
    var startIndex: Self.Index { get } 

    /// The collection's "past the end" position. 
    /// 
    /// `endIndex` is not a valid argument to `subscript`, and is always 
    /// reachable from `startIndex` by zero or more applications of 
    /// `successor()`. 
    var endIndex: Self.Index { get } 

    /// Returns the first element of `self`, or `nil` if `self` is empty. 
    var first: Self.Generator.Element? { get } 
} 

Если вы идете через файл Swift заголовок, вы можете увидеть определение массива следующим образом

struct Array<T> : CollectionType, SequenceType, _CollectionDefaultsType, _CollectionGeneratorDefaultsType, MutableCollectionType, Sliceable, _Sliceable, _DestructorSafeContainer { 

    /// The type of element stored by this `Array`. 
    typealias Element = T 

    /// Always zero, which is the index of the first element when non-empty. 
    var startIndex: Int { get } 

    /// A "past-the-end" element index; the successor of the last valid 
    /// subscript argument. 
    var endIndex: Int { get } 
    subscript (index: Int) -> T 

    /// Return a *generator* over the elements. 
    /// 
    /// - Complexity: O(1). 
    func generate() -> IndexingGenerator<[T]> 

    /// A type that can represent a sub-range of an `Array`. 
    typealias SubSlice = ArraySlice<T> 
    subscript (subRange: Range<Int>) -> ArraySlice<T> 
} 

Поглотитель StartIndex, ENDINDEX, во-первых, являются те, которые реализуются из протокола _CollectionDefaultsType, чей тип Self.Index. Теперь, если вы посмотрите на определение метода indexOf, оно реализовано как расширение протокола с типом Self.Index.

extension CollectionType where Generator.Element : Equatable { 

    /// Returns the first index where `value` appears in `self` or `nil` if 
    /// `value` is not found. 
    /// 
    /// - Complexity: O(`self.count`). 
    func indexOf(element: Self.Generator.Element) -> Self.Index? 
} 

Таким образом, индекс типа получает вывод на Int свыше двух реализации.

Кстати, если вы наберете в детскую площадку, чтобы увидеть индекс типа внутри массива, набрав Array.Index, автозаполнение показывает тип как Int,

enter image description here

+0

Я теряюсь, как эта строка «var startIndex: Int {get}» превращает эту другую строку «typealias Index: ForwardIndexType» в Int –

+0

«Индекс типов: ForwardIndexType» просто говорит, что тип Index - это то, что реализует «ForwardIndexType». Но вывод делается из «var startIndex: Int» внутри реализации массива. Так что подумайте об этом, например, протокол или реализация протокола не знает, что такое «Индекс», он просто знает, что существует некоторый тип индекса, но когда одной из переменных в реализации присваивается тип «Int», все остальные использование «Индекса» будет выведено как «Int» – Sandeep

+0

Спасибо, я начинаю понимать. Есть ли документы, на которые вы можете указать мне? В главе Prerelease iBook Swift 2.0 Protocol не говорится об этом. –

Смежные вопросы