2015-06-30 16 views
1

Swift中的詞典不符合ExtensibleCollectionType。因爲它會很容易把它擴大(它在某種程度上不與雨燕1.2的工作;利用斯威夫特2):詞典不符合ExtensibleCollectionType

extension Dictionary: ExtensibleCollectionType { 

    // ignoring this function 
    mutating public func reserveCapacity(n: Int) {} 

    mutating public func append(x: Dictionary.Generator.Element) { 
     self[x.0] = x.1 
    } 

    mutating public func extend<S : SequenceType where S.Generator.Element == Dictionary.Generator.Element>(newElements: S) { 
     for x in newElements { 
      self.append(x) 
     } 
    } 
} 

如果這樣做還可以添加字典(參見:Adding SequenceTypes

標準庫中沒有實現這個好處嗎?

+1

我看不到這樣做的有害後果。你應該提交一個錯誤報告。 –

+0

Swift 1.2中的錯誤(在Swift 2中解決了)還是在標準庫中實現這個錯誤? – Qbyte

+0

這是一個建議。 –

回答

0

從Xcode 7 beta 5開始ExtensibleCollectionType已重新命名(並重構)爲RangeReplaceableCollectionType。因此,符合本協議的意圖更加清晰:

新的協議只需要這個方法完全符合它:

mutating func replaceRange<C : CollectionType where C.Generator.Element == Generator.Element>(subRange: Range<Self.Index>, with newElements: C) 

,因爲這種操作ISN這沒有多大意義,任何無序集合不可預測(某些情況下的元素數除外)。此外,高度依賴於索引的默認實現和其他要求對於這樣的集合沒有用處。

總之,範圍的插入和替換應該是可預測的,並保留其他元素的結構/排序。因此Dictionaries和任何其他的無序集合都不應該符合這個特定的協議。