Last active
May 13, 2016 17:05
-
-
Save akisute/3045876b8efffdbacdb9 to your computer and use it in GitHub Desktop.
I have learned a "Gray Magic" of the Swift.
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 | |
class GrayShark { | |
var name:String | |
var howSwim:String | |
init(name:String, howSwim:String) { | |
self.name = name | |
self.howSwim = howSwim; | |
} | |
} | |
func letSharkSwim(shark:GrayShark) -> String { | |
return "\(shark.name) swims like '\(shark.howSwim)'." | |
} | |
// OK | |
letSharkSwim(GrayShark(name:"The Average Shark", howSwim:"Swim Swim Swim Lurk")) | |
// Error | |
// Could not find an overload for '__conversion' that accepts the supplied arguments | |
//letSharkSwim(nil) | |
// Here I cast a couple of "Gray Magics" of the swift language! | |
// http://vperi.com/2014/06/06/opt-in-type-casting-in-swift/ | |
// http://swift.sh/topic/80/swift/ | |
// | |
// There are several Gray Magics available in the article above, like: | |
// - nil is a singleton instance of the NilType (and we can make a extension of NilType) | |
// - @conversion func __conversion() -> Type for custom type conversions (also works for as operators as well) | |
// I believe we can omit @conversion attribute | |
// - Optional<T> is actually a enum which has 2 values, None and Some<T> (it's written in swift standard header so not that graymagic-ish) | |
// | |
// Here are some additional Gray Magics I've learned after some investigation: | |
// - ImplicitlyUnwrappedOptional<T> is, on the other hand, struct! | |
// - implement LogicValue protocol to be used in logical statement (e.g. if) | |
// - Reflectable protocol found... hmm looks like this could be really interesting magical source... XD | |
extension NilType { | |
@conversion func __conversion() -> (GrayShark) { | |
return GrayShark(name:"Gray Shark", howSwim:"UNBELIEVABLE POWERRRRRRRR") | |
} | |
} | |
// Enough long stories. Lets try it out. | |
// Oh my goodness. It worked. | |
letSharkSwim(nil) | |
let eof = "EOF" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment