2016-04-10 5 views
1

Каков правильный способ ограничения этого расширения? Мои испытания не увенчались успехом.Расширение массива словарей с помощью Swift 2.2

Например:

extension CollectionType where Generator.Element: [T.Key:Self.Value], T: DictionaryLiteralConvertible, T.Key: StringLiteralConvertible, T.Value: Encodable { 
+0

Это выглядит очень похоже: http://stackoverflow.com/questions/31956520/how-can-i-define-an-extension-to-collectiontype-so-that-its-methods-are-availabl. –

+0

Просто чтобы вы знали OP, связанный с Ar тип T был переименован в Element. – BallpointBen

ответ

5

Xcode 8 бета • Свифта 3

protocol Encodable { 
    var hashValue: Int { get } 
} 
extension Int: Encodable { } 

extension Collection where Iterator.Element == [String: Encodable] { 
    var total: Int { 
     return reduce(0) {$0 + $1.values.reduce(0) {$0 + $1.hashValue}} 
    } 
} 

let dictionaries:[[String: Encodable]] = [["One":1],["Two":2],["Three":3, "Four":4]] 

dictionaries.total // 10 

Xcode 7.3.1 • Swift 2.2.1

protocol Encodable { 
    var hashValue: Int { get } 
} 

extension Int: Encodable { } 

extension CollectionType where Generator.Element == [String: Encodable] { 
    var total: Int { 
     return reduce(0) {$0 + $1.values.reduce(0) {$0 + $1.hashValue}} 
    } 
} 

let dictionaries:[[String: Encodable]] = [["One":1],["Two":2],["Three":3, "Four":4]] 

dictionaries.total // 10 
+0

Не могли бы вы объяснить, почему _ArrayType с подчеркиванием? – Laurent

+0

http://swiftdoc.org/v2.2/protocol/_ArrayType/ –

+0

http://swiftdoc.org/v2.2/protocol/_ArrayType/hierarchy/ –