This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
extension Collection { | |
func firstMap<T>(_ transform: @escaping (Element) -> T?) -> T? { | |
for element in self { | |
if let transformed = transform(element) { | |
return transformed | |
} | |
} | |
return nil |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Sequence { | |
public func inspect( | |
_ body: (Element) throws -> Void | |
) rethrows -> Self { | |
for element in self { | |
try body(element) | |
} | |
return self | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension URLSession { | |
func dataTask(with url: URL, completionHandler: @escaping (Result<Data, AnyError>) -> Void) -> URLSessionTask { | |
return dataTask(with: url, completionHandler: { (data, response, error) in | |
if let error = error { | |
let anyError = AnyError(error) | |
completionHandler(Result.failure(anyError)) | |
} else if let data = data { | |
completionHandler(Result.success(data)) | |
} else { | |
let anyError = AnyError(NSError(domain: "my domain", code: 500, userInfo: nil)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Weave possible nsnull values to turn them into a nil. | |
func convertNSNullToNil<T>(_ data: T?) -> T? { | |
switch data { | |
case is NSNull: return nil | |
case is [NSNull]: return nil | |
case is [NSNull: Any]: return nil | |
default: return data | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// Naive implementation of a piping operator. | |
func stringToInt(_ str: String) -> Int { | |
return Int(str)! //force unwrap for demonstration purposes | |
} | |
func intToFloat(_ int: Int) -> Float { |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UIView: Showable { | |
} | |
protocol Showable { | |
func layout() |