gpt4 book ai didi

swift - 使用 Swift 2.2 扩展字典数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:06:17 26 4
gpt4 key购买 nike

限制此扩展的正确方法是什么?我的试验没有成功。

例如:

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

最佳答案

Xcode 8 测试版 • Swift 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

关于swift - 使用 Swift 2.2 扩展字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com