Swift 4中的新特性(Whatʼs New in Swift

2017-12-12  本文已影响26人  sayHellooX

Dictionary

let sque = zip(97..., ["a", "b", "c", "d", "e", "f"])
var dic = Dictionary(uniqueKeysWithValues: sque)
print(dic)
//[100: "d", 101: "e", 99: "c", 97: "a", 98: "b", 102: "f"]
let arr = Array(sque)
print(arr)
//[(97, "a"), (98, "b"), (99, "c"), (100, "d"), (101, "e"), (102, "f")]
dic = Dictionary(uniqueKeysWithValues: arr)
print(dic)
//[100: "d", 101: "e", 99: "c", 97: "a", 98: "b", 102: "f"]
let arr = [("a", 2), ("b", 3), ("b", 4), ("a", 4)]
var dic = Dictionary.init(arr) { (first, _) in
      first
}
print(dic)
//["b": 3, "a": 2]
dic = Dictionary(arr) { (_, last) in
      last
}
print(dic)
//["b": 4, "a": 4]
let sortingHat = [
            ("a", "1"), ("b", "2"),
            ("c", "4"), ("d", "3"), ("e", "5"), ("a", "6"),
            ("a", "7"), ("b", "8"),
            ("c", "9"), ("f", "10")
        ]
let houses = Dictionary(
        sortingHat.map { ($0.0, [$0.1]) },
         uniquingKeysWith: { (current, new) in
         return current + new
})
print(houses)
//["b": ["2", "8"], "a": ["1", "6", "7"], "c": ["4", "9"], "e": ["5"], "f": ["10"], "d": ["3"]]

计算字符的个数

let str = "Sometimes affection is a shy flower that takes time to blossom."
var frequencies: [Character: Int] = [:]
let baseCounts = zip(
      str.filter { $0 != " " }.map { $0 },
      repeatElement(1, count: Int.max))
frequencies = Dictionary(baseCounts, uniquingKeysWith: +)
print(frequencies)
//["w": 1, "n": 1, ".": 1, "o": 6, "f": 3, "k": 1, "t": 7, "S": 1, "b": 1, "a": 4, "i": 4, "r": 1, "m": 4, "c": 1, "e": 6, "s": 6, "l": 2, "y": 1, "h": 2]

还有很多高级的用法,大家可以去查下资料


let dic = ["a": 1, "b": 2, "c": 3]
var swift3 = dic["a"]  或者  
swift3 = dic["a"] ?? 0

var swift4 = dic["a", default: 0]

上面的例子可以通过如下的代码实现

let str = "Sometimes affection is a shy flower that takes time to blossom."
var frequencies: [Character: Int] = [:]
let newStr = str.filter { $0 != " "}
newStr.map {
     return frequencies[$0, default:0] += 1
}
print(frequencies)
//结果同上
let names = ["Harry", "ron", "Hermione", "Hannah", "neville", "pansy", "Padma"].map { $0.capitalized }
 let nameList = Dictionary(grouping: names) { $0.first!}
print(nameList)
//["H": ["Harry", "Hermione", "Hannah"], "R": ["Ron"], "N": ["Neville"], "P": ["Pansy", "Padma"]]
上一篇 下一篇

猜你喜欢

热点阅读