Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Thinking

Swift Thinking

I talk about operator overloading and easy type safe JSON parsing in Swift.

Keith Smiley

June 26, 2014
Tweet

More Decks by Keith Smiley

Other Decks in Technology

Transcript

  1. operator infix .... {} @infix func .... (lhs: Int, rhs:

    Int) -> Range<Int> { return Range(start: Int(arc4random_uniform(UInt32(lhs))), end: Int(arc4random_uniform(UInt32(rhs)))) }
  2. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\w+" options:0 error:nil]; NSRange range =

    NSMakeRange(0, string.length) NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:range]; if (numberOfMatches > 0) { ... }
  3. let regex = NSRegularExpression(pattern: "\\w+", options: nil, error: nil) let

    range = NSMakeRange(0, countElements(string)) let numberOfMatches = regex.numberOfMatchesInString(string, options: nil, range: range) if numberOfMatches > 0 { ... }
  4. -- Haskell matches :: String -> Bool matches x =

    x =~ "\\w+" # Ruby if string =~ /\w+/ ... end # Shell script... if [[ $string =~ "\w+" ]]; then ... fi
  5. // This ~= operator ensures that indexPath.row // is found

    in the range on the right. if 1...list.count ~= indexPath.row { ... } // Check to see if the key is contained in the array. if ["foo", "bar"] ~= key { ... }
  6. if let userDict = JSON as? NSDictionary { if let

    username = userDict.objectForKey("username") as? String { println(username) } }
  7. if let users = JSON as? NSDictionary[] { for userDict

    in users { if let username = userDict.objectForKey("username") as? String { println(username) } } }
  8. if let repos = githubJSON as? NSDictionary[] { for repoDict

    in repos { if let permissions = repoDict.objectForKey("permissions") as? NSDictionary { if let isAdmin = permissions.objectForKey("admin") as? Bool { if isAdmin { println("They are an admin!") } } } } }
  9. data User = User { username :: String , userID

    :: Integer } deriving (Show) instance FromJSON User where parseJSON (Object j) = User <$> (j .: "username") <*> (j .:? "id") case decode JSON :: Maybe User of Just user -> print user Nothing -> error "Invalid JSON"