Skip to content

Instantly share code, notes, and snippets.

@samdmarshall
Last active January 25, 2017 16:05
Show Gist options
  • Save samdmarshall/a7a657c8d1a1634d1e734bb17a11b31a to your computer and use it in GitHub Desktop.
Save samdmarshall/a7a657c8d1a1634d1e734bb17a11b31a to your computer and use it in GitHub Desktop.
// Intention: query a dictionary for a key-value pair, take the value as a path that needs to be expanded (tilde -> abspath)
// and then make it available to use.
let path_value = arguments["path"] ?? "" // the `?? ""` makes this a `String` and not an `Any`
var path = NSString.init(string:"\(keychain_path_value)") // this will accept an `Any` or a `String` as the type to
// subsitute when creating the `NSString` type object
if !path.isEqual(to:"") { // "if the string has contents, then expand the path"
path = path.expandingTildeInPath as NSString // cast `as NSString` is necessary because it returns a `String`
}
//
// So without the `?? ""` on line 1, if there is no value in the `argument` dictionary for the key `"path"`, that will return
// an `Any` object which will case the `NSString` object that is created on line 2 to return as `nil`, not as a valid
// `NSString` object. I don't like that the introduction of a single bridge call into Objective-C here makes all following
// statements that use that variable contain more risk due to the possibility of the optional value.
//
// Additionally, with this specific code, you can satisfy the swift (3.0.2) compiler with and without the `?? ""` in line 1
// because of the typing of the code. Which means I could remove it, this could still be seen as "valid" without raising
// any warnings and be fundamentally poorly written code for handling the intention properly. Furthermore, the default value
// assignment can be removed without making any indication about the type system and implication of the changes as such.
//
@Frizlab
Copy link

Frizlab commented Jan 25, 2017

Would do something like

guard let raw_path = arguments["path"] as? String else {fail...}
let path = (raw_path as NSString).expandingTildeInPath

Not exactly your original code, but much more type safe (and dare I say, elegant 😄).

Also, question: Why do you check if the string is empty? Also, str == "" or even better str.empty seems prettier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment