Skip to content

Instantly share code, notes, and snippets.

@rodericj
Created June 21, 2014 00:30
Show Gist options
  • Save rodericj/e84e827be93d43ef7b40 to your computer and use it in GitHub Desktop.
Save rodericj/e84e827be93d43ef7b40 to your computer and use it in GitHub Desktop.
import Cocoa
class StringHolder {
var a : String?
var b : String?
var c : String?
func naiveDescription() -> String {
return a! + b! + c!
}
func preferredDescription() -> String {
var builtString : String = ""
if let defA = a? {
builtString += defA
}
if let defB = b? {
builtString += defB
}
if let defC = c? {
builtString += defC
}
return builtString
}
}
var holder = StringHolder()
holder.a = "a String "
holder.b = "b string"
println(holder.preferredDescription()) // successfully prints the description
println(holder.naiveDescription()) // since c is not set and it is forced, this crashes
@joshaber
Copy link

Something like this would be a bit more general:

func preferredDescription() -> String {
    let strings = [a, b, c]
    return strings.map({ $0 ? $0! : "" }).reduce("", combine: +)
}

@rodericj
Copy link
Author

@joshaber yes that is concise. I'll take it. Thank you for that.

@rodericj
Copy link
Author

rodericj commented Aug 4, 2014

Awww, @joshaber looks like they broke this in the latest. wah waaaahhh. I'll play around

@rodericj
Copy link
Author

rodericj commented Aug 4, 2014

Looks like it may just be the implicit comparison to nil. Got it.

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