Skip to content

Instantly share code, notes, and snippets.

@benrudhart
Created May 27, 2015 12:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save benrudhart/89f0b5711c96834064be to your computer and use it in GitHub Desktop.
Save benrudhart/89f0b5711c96834064be to your computer and use it in GitHub Desktop.
A Swift protocol that is using an enum with a generic associated type
import Foundation
import UIKit
//: # The problem: Protocol that is using an enum with generic associated type
enum GenericEnum<T> {
case Unassociated
case Associated(T)
}
protocol AssociatedProtocol: class {
typealias Association
func foo() -> GenericEnum<Association>
}
//: ## Short example of the issue
//: Protocol can only be used as a generic constraint because it has associated type requirements
let bar = [AssociatedProtocol<String>]()
//: ## Long example of the issue
// working examples
class StringProtocol: AssociatedProtocol {
func foo() -> GenericEnum<String> {
// todo...
return .Associated("foo")
}
}
class StringListProtocol: AssociatedProtocol {
func foo() -> GenericEnum<[String]> {
// todo...
return .Associated(["foo"])
}
}
let aStringListProtocol = StringListProtocol()
let returnedEnum = aStringListProtocol.foo()
switch returnedEnum {
case .Unassociated:
println("Unassociated")
case .Associated(let strings):
println("strings: \(strings)")
}
// not working
class StringProtocolList: AssociatedProtocol {
typealias StringProtocolArray = [AssociatedProtocol]
var stringProtocols: StringProtocolArray = []
func foo() -> GenericEnum<StringProtocolArray> {
let stringProtocol = StringProtocol()
stringProtocols.append(stringProtocol)
// todo...
return .Associated(stringProtocols)
}
}
let list = StringProtocolList()
let foos = list.foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment