Created
June 18, 2018 14:24
-
-
Save dcilia/90c495e9912a4551c3313e1712c07364 to your computer and use it in GitHub Desktop.
Generic Constraints Swift 4.2
This file contains 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 Cocoa | |
protocol OperationType {} | |
protocol ObserverType { | |
func did<T>(start operation : T) -> Void | |
} | |
extension ObserverType { | |
func did<T>(start operation : T) -> Void { | |
let s = type(of: self) | |
print(#function + "\(s)") | |
} | |
} | |
public final class Async : OperationType { | |
var observers : [ObserverType] = [] | |
var observersAny : [AnyObserver] = [] | |
} | |
public class AsyncObserver : ObserverType { | |
func did<T>(start operation: T) { | |
print(#function) | |
} | |
func did<T>(start operation: T) where T : OperationType { | |
print(#function + " T : OperationType") | |
} | |
func did<T>(start operation: T) where T : Async { | |
print(#function + " T : Async") | |
} | |
} | |
public final class AnyObserver : ObserverType { | |
private var _value : Any | |
public func value<T>() -> T { | |
return _value as! T | |
} | |
public func setValue<T>(newValue : T) -> Void { | |
_value = newValue | |
} | |
public init<T>(observer : T) { | |
_value = observer | |
} | |
func did<T>(start operation: T) where T : Async { | |
print(#function + " T : Async") | |
} | |
func did<T>(start operation: T) { | |
print(#function) | |
} | |
func did<T>(start operation: T) where T : OperationType { | |
print(#function + " T : OperationType") | |
} | |
} | |
//Setup | |
let operation = Async() | |
let obs = AsyncObserver() | |
let obsAny = AnyObserver(observer: obs) | |
//Test A: | |
operation.observers.append(obs) | |
operation.observers.forEach { $0.did(start: operation) } | |
obs.did(start: operation) | |
//Test B: | |
operation.observersAny.append(obsAny) | |
operation.observersAny.forEach { | |
let val : ObserverType = $0.value() | |
val.did(start: operation) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment