Last active
August 29, 2015 14:15
-
-
Save rnapier/df2eec14b19c84d5eef0 to your computer and use it in GitHub Desktop.
Alternate if-let escape patterns (compare http://ericasadun.com/2015/02/16/swift-linearizing-code/)
This file contains hidden or 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 Foundation | |
| func BuildError(val: Int, msg: String) -> NSError { return NSError() } | |
| func Error<T>(errorPointer: NSErrorPointer, val: Int, msg: String) -> T? { | |
| if errorPointer != nil { | |
| errorPointer.memory = BuildError(val, msg) | |
| } | |
| return nil | |
| } | |
| // This is the style I've been using. Note that I just pass errorPointer along to NSData() | |
| // I don't create a new Error? variable | |
| func StringFromURL(url : NSURL, error errorPointer : NSErrorPointer) -> NSString? { | |
| if let | |
| data = NSData(contentsOfURL:url, options: NSDataReadingOptions(rawValue:0), error: errorPointer) { | |
| return NSString(data: data, encoding: NSUTF8StringEncoding) | |
| ?? Error(errorPointer, 1, "Unable to build string from data") | |
| } else { | |
| return nil | |
| } | |
| } | |
| // I haven't really tried this style yet, but with Swift 1.2's multi-let, | |
| // this is probably a nicer idea, and I'll probably try it in the future. | |
| // See how ?? Error() basically converts a non-NSErrorPointer function into an NSErrorPointer function | |
| func StringFromURL2(url : NSURL, error errorPointer : NSErrorPointer) -> NSString? { | |
| if let | |
| data = NSData(contentsOfURL:url, options: NSDataReadingOptions(rawValue:0), error: errorPointer), | |
| string = NSString(data: data, encoding: NSUTF8StringEncoding) | |
| ?? Error(errorPointer, 1, "Unable to build string from data") { | |
| return string | |
| } | |
| return nil | |
| } | |
| // This is a new style I've been exploring that exploits Swift 1.2's | |
| // new feature that a let must be assigned to exactly once. This provides | |
| // nice error checking against accidentally forgetting to set result, or | |
| // setting it multiple times. | |
| func StringFromURL3(url : NSURL, error errorPointer : NSErrorPointer) -> NSString? { | |
| let result: NSString? | |
| if let | |
| data = NSData(contentsOfURL:url, options: NSDataReadingOptions(rawValue:0), error: errorPointer) { | |
| result = NSString(data: data, encoding: NSUTF8StringEncoding) | |
| ?? Error(errorPointer, 1, "Unable to build string from data") | |
| } else { | |
| result = nil | |
| } | |
| return result | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment