用map 、flatMap 、 filter、 reduce 及扩展等强行打造自己的小作坊
某天你跟后台发生矛盾了,直接给你返回一串字符串...(⊙o⊙)?
let scoreStr = "小东:87;小龙:81;小天:97;小六:76;小张:54;小熙:94;小西:20;小伍:76;小迪:64;小马:36"
extension String {
/*
* 切割字符串->数组
*/
func split(str: String) -> [String] {
return self.componentsSeparatedByString(str)
}
}
//总分 A作坊 整理 -> 过滤车间 -> 打包车间
let t1 = scoreStr.split(";")
.flatMap{ Double($0.split(":")[1]) }
.reduce(0, combine: +) // = 685
//总分 B作坊 整理 -> 多功能车间
let t2 = scoreStr.split(";")
.reduce(0) { (r, c) -> Double in
return r + Double(c.split(":")[1])!
} // = 685
//取及格分数的人
let p = scoreStr.split(";").filter {
Double($0.split(":")[1])! > 60
}
print(p) // = ["小东:87", "小龙:81", "小天:97", "小六:76", "小熙:94", "小伍:76", "小迪:64"]
//取小天的分数
let xiaoTian = scoreStr.split(";")
.reduce(0){ (r,c) -> Double in
if c.hasPrefix("小天") {
return Double(c.split(":")[1])!
}
return r
}
//那么一个个取也不是办法,要取其他人的咋办,好办,交给小作坊
extension String {
/*
*专为该字符串服务的临时小作坊
* 输入名字 —> 分数
*/
func find(str:String) -> Double {
let rs = self.split(";")
.reduce(0){ (r,c) -> Double in
if c.hasPrefix(str) {
return Double(c.split(":")[1])!
}
return r
}
return rs
}
}
scoreStr.find("小龙") // = 81
//平均分
let average = totalScore/Double(scoreStr.split(";").count) // = 68.5
///#变成数组
let strArr = scoreStr.split(";")
print(strArr) // = ["小东:87", "小龙:81", "小天:97", "小六:76", "小张:54", "小熙:94", "小西:20", "小伍:76", "小迪:64", "小马:36"]
///#变成字典
//#简单循环模式
var dict = [String:Int]()
scoreStr.split(";").forEach {
let k = $0.split(":")[0]
let v = $0.split(":")[1]
dict[k] = Int(v)
}
print(dict) // = ["小六": 76, "小天": 97, "小龙": 81, "小伍": 76, "小东": 87, "小马": 36, "小熙": 94, "小西": 20, "小迪": 64, "小张": 54]
/*
let dict2 = scoreStr.split(";")
.map { (c) -> [String:Int] in
let k = c.split(":")[0]
let v = c.split(":")[1]
return [k:Int(v)!]} */
///#字典变回字符串
let rStr = dict.reduce("") { (r,c) -> String in
var r = r
r += (c.0 + ":" + String(c.1) + ";")
return r
}
print(rStr) // = 小六:76;小天:97;小龙:81;小伍:76;小东:87;小马:36;小熙:94;小西:20;小迪:64;小张:54;
/*
let rStr = dict.reduce("") { (r, c) in
return r + (c.0 + ":" + String(c.1) + ";")
}
*/