Следующий словарь создаст этот словарь:
["Burnley": [1.5, 2.5], "West Ham": [2.5, 0.5]]
Вы не указали, что есть какой-либо способ определить, кто из них «домашний», а какой «отсутствующий». Если вы не можете, Dictionary
- лучшее, что вы можете сделать.
public extension Dictionary {
/// Group key-value pairs by their keys.
///
/// - Parameter pairs: Either `Swift.KeyValuePairs<Key, Self.Value.Element>`
/// or a `Sequence` with the same element type as that.
/// - Returns: `[ KeyValuePairs.Key: [KeyValuePairs.Value] ]`
init<Value, KeyValuePairs: Sequence>(grouping pairs: KeyValuePairs)
where
KeyValuePairs.Element == (key: Key, value: Value),
Self.Value == [Value]
{
self =
Dictionary<Key, [KeyValuePairs.Element]>(grouping: pairs, by: \.key)
.mapValues { $0.map(\.value) }
}
/// Group key-value pairs by their keys.
///
/// - Parameter pairs: Like `Swift.KeyValuePairs<Key, Self.Value.Element>`,
/// but with unlabeled elements.
/// - Returns: `[ KeyValuePairs.Key: [KeyValuePairs.Value] ]`
init<Value, KeyValuePairs: Sequence>(grouping pairs: KeyValuePairs)
where
KeyValuePairs.Element == (Key, Value),
Self.Value == [Value]
{
self.init( grouping: pairs.map { (key: $0, value: $1) } )
}
}
import Foundation
extension Market {
enum DecodingError: Error {
case invalidFormat(String)
case notANumber(String)
}
static func decode(_ strings: [String]) throws -> [ String: [Double] ] {
.init(
grouping: try strings.map {
let nameAndBet = $0.components(separatedBy: " Total Goals - Over/Under ")
guard nameAndBet.count == 2
else { throw DecodingError.invalidFormat($0) }
let betString = nameAndBet[1]
guard let bet = Double(betString)
else { throw Market.DecodingError.notANumber(betString) }
return (teamName: nameAndBet[0], bet)
}
)
}
}
try Market.decode(marketItems)