Vince
1
In Objective-C, a protocol can be stored as a parameter because it is a class. Can the corresponding protocol also be supported as a parameter in swift?
ibex10
2
Yes, if the following constraints hold.
// Some protocol
protocol Foo {
...
}
// Concrete type for Key conforms to Foo, and is also Hashable
Dictionary <Key, Value> where Key: Foo & Hashable
// Or concrete type for Value conforms to Foo
Dictionary <Key, Value> where Key: Hashable, Value: Foo
Vince
3
Thanks for your reply, I want to implement something like this in swift.Use swift's classes and protocols
class Detection {
var prots: [String] = []
func register(_ prot: Protocol) {
let value = NSStringFromProtocol(prot)
prots.append(value)
}
func conforms<T: NSObject>(_ element: T) -> Bool {
var result: Bool = false
prots.forEach { value in
if let prot = NSProtocolFromString(value) {
result = element.conforms(to: prot)
return
}
}
return result
}
}
You could do this:
final class Detector {
var types: [any Any.Type] = []
func register(_ type: any Any.Type) {
types.append(type)
}
func check(_ instance: some Any) -> Bool {
func instanceIsOfType<T>(_: T.Type) -> Bool {
return instance is T
}
return types.contains(where: { type in
#if hasFeature(ImplicitOpenExistentials)
return instanceIsOfType(type)
#else
// By default, the Swift 5 language mode doesn't support implicitly
// opening `any Any.Type` so we have to use this workaround.
// See: https://forums.swift.org/t/why-is-any-any-type-different-to-any-any-type/62099/5
return _openExistential(type, do: instanceIsOfType(_:))
#endif
})
}
}
You can use it like this:
class A {}
final class B: A {}
let detector = Detector()
detector.check(5) // false
detector.register((any BinaryInteger).self) // register a protocol type
detector.check(5) // true
detector.check(B()) // false
detector.register(A.self) // register a class type
detector.check(B()) // true
detector.check("str") // false
detector.register(String.self) // register a value type
detector.check("str") // true
However, this use of types is pretty unusual for Swift.