JetForMe
(Rick M)
May 11, 2023, 10:41am
1
I'm trying to convert an old Obj-C project to Swift. I'm using an esoteric serialization protocol called Hessian that gets configured with calls like this:
[CWHessianUnarchiver setProtocol: @protocol(MissionProtocol) forClassName: @"com.some.java.server.class.ClientV1Mission"];
…
@protocol MissionProtocol
// Properties…
@end
In Swift, the calls look like this, but this isn’t quite right, and I'm not sure how to write it:
CWHessianUnarchiver.setProtocol(MissionProtocol.Type, forClassName: "com.some.java.server.class.ClientV1Mission")
But I get {Cannot convert value of type '(any MissionProtocol.Type).Type' to expected argument type 'Protocol?'" for the setProtocol
call. How should I pass this?
bbrk24
May 11, 2023, 11:09am
2
Objective-C Protocol
objects, like Swift metatypes, are spelled P.self
, not P.Type
.
3 Likes
Kyle-Ye
(Kyle)
May 11, 2023, 12:16pm
3
The 2 posts may help solve your problem.
We have an ObjC API which receive a Protocol instance and return Any?.
// Imported ObjectiveC API
func resolve(_ p: Protocol) -> Any?
// Swift Side Code
@objc protocol P: NSObjectProtocol {
func hello()
}
func test() {
let p = resolve(P.self) as? P
p?.hello()
}
In Swift side, we'd like to wrap the API to make it more swift-friendly.
func resolve2<T>(_ t: T.Type) -> T? {
return resolve(t) as? T //
return resolve(t.self) as? T //
return resolve(T.self) as? T //
…
Metatypes are pretty useful in Swift, and you have certainly used it in multiple occasions. Unfortunately they look pretty weird in code, which can cause some confusion when trying to understand what they really are.
1 Like
JetForMe
(Rick M)
May 11, 2023, 10:42pm
4
I tried that, but it didn't work. However, I just tried it again, and it works. I must've not tried. But now I'm questioning my sanity. Thanks!
2 Likes