Skip to content

Instantly share code, notes, and snippets.

@dfrib

dfrib/misc.swift Secret

Last active July 6, 2016 21:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfrib/01e4bf1020e2e39dbe9cfb14f4165656 to your computer and use it in GitHub Desktop.
Save dfrib/01e4bf1020e2e39dbe9cfb14f4165656 to your computer and use it in GitHub Desktop.
Misc Swift
protocol Homogenous {
func foo(_: Self)
}
extension Homogenous {
func foo(_: Self) { }
}
extension Int: Homogenous { }
let a: Int = 1
let b: String = "one"
/* Generally, we can't type check using 'is' against a homogenous protocol,
but if the variable we are type checking is an optional, we can.
Why is this? */
let bar: Int? = a
bar is Homogenous // true
Optional(a) is Homogenous // true
let baz: String? = b
baz is Homogenous // false
/* generally:
error: protocol 'Homogenous' can only be used as a generic constraint
because it has Self or associated type requirements */
//a is Homogenous
//b is Homogenous
/* Can we emulate it with a simple
enum wrapper of our own? Nope. */
enum Wrapper<T> {
case Some(T)
case None
}
let foo = Wrapper.Some(a)
//foo is Homogenous
/* error: protocol 'Homogenous' can only ... */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment