Created
July 13, 2022 14:55
-
-
Save evnik/c88963323dd7083d6e8a4adac5bc8e58 to your computer and use it in GitHub Desktop.
Playing around casting of generic protocol
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
protocol AnyProtocol { | |
func checkAndRemove<T>(_ predicate: (T) -> Bool) -> Bool | |
func checkAndRemove<T>() -> T? | |
func insert<T>(_ value: T) | |
} | |
protocol ProtocolA: AnyProtocol { | |
associatedtype T | |
var size: Int { get } | |
func insert(value: T) | |
func remove() -> T | |
} | |
extension ProtocolA { | |
func checkAndRemove<T>(_ predicate: (T) -> Bool) -> Bool { | |
if size > 0, let removed = remove() as? T, predicate(removed) { | |
return true | |
} | |
return false | |
} | |
func checkAndRemove<T>() -> T? { | |
if size > 0 { | |
return remove() as? T | |
} | |
return nil | |
} | |
func insert<T>(_ value: T) { | |
if let value = value as? Self.T { | |
insert(value: value) | |
} | |
} | |
} | |
class ClassA<T: Comparable>: ProtocolA { | |
private var array = [T]() | |
var size: Int { | |
array.count | |
} | |
func insert(value: T) { | |
array.append(value) | |
array.sort() | |
} | |
func remove() -> T { | |
array.removeFirst() | |
} | |
} | |
let objArray: [AnyProtocol] = [ClassA<Int>()] | |
objArray.first?.insert(42) | |
objArray.first?.insert(0) | |
objArray.forEach({ obj in | |
if obj.checkAndRemove({ $0 == 0 }) { | |
print("removed 0") | |
} | |
}) | |
let removed: Int? = objArray.first?.checkAndRemove() | |
print(removed ?? "nothing") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment