Skip to content

Instantly share code, notes, and snippets.

@genedelisa
Created February 2, 2015 10:57
Show Gist options
  • Save genedelisa/b40710734f3fd0538c8a to your computer and use it in GitHub Desktop.
Save genedelisa/b40710734f3fd0538c8a to your computer and use it in GitHub Desktop.
Swift StringLiteralConvertible
public class Foo : StringLiteralConvertible {
var num:Int = 0
required public init(stringLiteral value: StringLiteralType) {
self.num = value.toInt()!
// of course you can do something more complicated by parsing the value.
}
public typealias UnicodeScalarLiteralType = StringLiteralType
convenience required public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(stringLiteral: value)
}
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
required convenience public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(stringLiteral: value)
}
}
var foo:Foo = "1"
@genedelisa
Copy link
Author

StringLiteralConvertible conforms to protocol ExtendedGraphemeClusterLiteralConvertible which in turn conforms to UnicodeScalarLiteralConvertible. That is why you need three inits.

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