Skip to content

Instantly share code, notes, and snippets.

@walkingway
Forked from chriseidhof/parsing.swift
Last active January 31, 2016 10:36
Show Gist options
  • Select an option

  • Save walkingway/1dcc62d9672bdb15d07c to your computer and use it in GitHub Desktop.

Select an option

Save walkingway/1dcc62d9672bdb15d07c to your computer and use it in GitHub Desktop.
JSON Parsing in Swift
// This code accompanies a blog post: http://chris.eidhof.nl/posts/json-parsing-in-swift.html
//
// As of Beta5, the >>= operator is already defined, so I changed it to >>>=
import Foundation
let parsedJSON : [String:AnyObject] = [
"stat": "ok",
"blogs": [
"blog": [
[
"id" : 73,
"name" : "Bloxus test",
"needspassword" : true,
"url" : "http://remote.bloxus.com/"
],
[
"id" : 74,
"name" : "Manila Test",
"needspassword" : false,
"url" : "http://flickrtest1.userland.com/"
]
]
]
]
struct Blog {
let id: Int
let name: String
let needsPassword: Bool
let url: NSURL
}
extension Blog: CustomStringConvertible {
var description: String {
return "Blog { id = \(id), name = \(name), needsPassword = \(needsPassword), url = \(url)"
}
}
public func parseJSON() {
let blogs = dictionary(parsedJSON, key: "blogs") >>>= {
array($0, key: "blog") >>>= {
// 此 map 后跟着一个闭包
join($0.map(parseBlog))
}
}
print(blogs)
}
func parseBlog(blog: AnyObject) -> Blog? {
let myBlog = curry{id, name, needsPassword, url in Blog(id: id, name: name, needsPassword: needsPassword, url: url)}
return asDict(blog) >>>= {
// $0 代表了 asDict(blog)
myBlog <*> int($0, key: "id")
<*> string($0, key: "name")
<*> bool($0, key: "needspassword")
<*> (string($0, key: "url") >>>= toURL)
}
}
// 将数组中的 optional 元素拆包后组合起来,只要有一个为元素为 nil 整个结果就为 nil
func join<A>(elements: [A?]) -> [A]? {
var result: [A] = []
for element in elements {
if let x = element {
result += [x]
} else {
return nil
}
}
return result
}
func asDict(x: AnyObject) -> [String: AnyObject]? {
return x as? [String: AnyObject]
}
func array(input: [String:AnyObject], key: String) -> [AnyObject]? {
let mayArray: AnyObject? = input[key]
return mayArray >>>= {$0 as? [AnyObject]}
}
func dictionary(input: [String:AnyObject], key: String) -> [String:AnyObject]? {
return input[key] >>>= {$0 as? [String:AnyObject]}
}
func string(input:[String:AnyObject], key: String) -> String? {
return input[key] >>>= {$0 as? String}
}
func number(input: [NSObject:AnyObject], key: String) -> NSNumber? {
return input[key] >>>= {$0 as? NSNumber}
}
func int(input: [NSObject:AnyObject], key: String) -> Int? {
return number(input, key: key).map{$0.integerValue}
}
func bool(input:[NSObject:AnyObject], key: String) -> Bool? {
return number(input, key: key).map{$0.boolValue}
}
func toURL(urlString: String) -> NSURL? {
return NSURL(string: urlString)
}
func flatten<A>(x:A??) -> A? {
guard let x = x else {return nil}
return x
}
// 这个方法很简单,其实就是替代 if let 的,用于将左边的参数放到右边的表达式中最终得出结果
// usege:参数 >>>= 表达式
infix operator >>>= {}
func >>>= <A,B>(optional: A?, f: A -> B?) -> B? {
// map 方法针对 optional,If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`.
return flatten(optional.map(f))
}
// 本质也是替代 if let 的,只要左边的表达式存在,右边的参数也存在
// // usege:表达式 >>>= 参数
infix operator <*> {associativity left precedence 150}
func <*><A, B>(l: (A -> B)?, r: A?) -> B? {
guard let l1 = l, let r1 = r else {return nil}
return l1(r1)
}
func curry<A,B,R>(f:(A,B) -> R) -> (A -> (B -> R)) {
return {a in {b in f(a,b)}}
}
func curry<A,B,C,R>(f:(A,B,C) -> R) -> A -> B -> C -> R {
return {a in {b in {c in f(a,b,c)}}}
}
func curry<A,B,C,D,R>(f:(A,B,C,D) -> R) -> A -> B -> C -> D -> R {
return {a in {b in {c in {d in f(a,b,c,d)}}}}
}
// This code is provided under the MIT license:
// Copyright (c) 2014 Chris Eidhof
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment