Skip to content

Instantly share code, notes, and snippets.

@networkextension
Created December 6, 2016 08:47
Show Gist options
  • Select an option

  • Save networkextension/246b590b44fd04f555fc7392449ae825 to your computer and use it in GitHub Desktop.

Select an option

Save networkextension/246b590b44fd04f555fc7392449ae825 to your computer and use it in GitHub Desktop.
json_filter.swift
let persons: [[String: Any]] = [["name": "Carl Saxon", "city": "New York, NY", "age": 44],
["name": "Travis Downing", "city": "El Segundo, CA", "age": 34],
["name": "Liz Parker", "city": "San Francisco, CA", "age": 32],
["name": "John Newden", "city": "New Jersey, NY", "age": 21],
["name": "Hector Simons", "city": "San Diego, CA", "age": 37],
["name": "Brian Neo", "age": 27]] //注意这家伙没有 city 键值
func infoFromState( state: String, persons: [[String: Any]])
-> Int {
// 先进行 flatMap 后进行 filter 筛选
// $0["city"] 是一个可选值,对于那些没有 city 属性的项返回 nil
// componentsSeparatedByString 处理键值,例如 "New York, NY"
// 最后返回的 ["New York","NY"],last 取到最后的 NY
let x = persons.flatMap( {
guard let x = $0["city"] else {return nil}
return (x as! String).components(separatedBy:", ").last })
.filter({$0 == state
}
)
return x.count
}
let count = infoFromState(state: "CA", persons: persons)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment