Last active
May 29, 2017 08:36
-
-
Save hlung/243974186c7f67ab3063fde5cf9d8c12 to your computer and use it in GitHub Desktop.
A Swift 3 example of mapValue(), a map() variant that only converts value of dictionary receiver and returns as a new dictionary instead of array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MapValueExample.swift | |
// ViKi | |
// | |
// Created by Thongchai Kolyutsakul on 29/5/17. | |
// | |
// | |
import Foundation | |
import SwiftyJSON | |
struct MyStruct { | |
let titles: [String: String] // keyed by language | |
init(json: JSON) { | |
self.titles = json["titles"].stringsDictionaryValue | |
} | |
} | |
private extension JSON { | |
// Converts receiver to [String: String], or empty [:] if cannot. | |
var stringsDictionaryValue: [String: String] { | |
return self.dictionaryValue.mapValues{ $0.stringValue } | |
} | |
} | |
private extension Dictionary { | |
// Maps only the values of receiver and returns as a new dictionary. | |
// Note: The traditional map function returns an array. | |
func mapValues<T>(_ transform: (Value)->T) -> Dictionary<Key,T> { | |
var resultDict = [Key: T]() | |
for (k, v) in self { | |
resultDict[k] = transform(v) | |
} | |
return resultDict | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment