-
-
Save marcosrocha85/920372648ffce2e2bf1cdea7cede687a to your computer and use it in GitHub Desktop.
A Swift protocol that is using an enum with a generic associated type
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 | |
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