An Hoa
An Hoa

Reputation: 1267

Conforming to Identifiable in Objective-C

I want to make existing Objective-C classes conform to the Identifiable protocol so that I could use them as list items in SwiftUI.

@interface MyClass: NSObject // What to do?
@end

Is there a good alternative that doesn't require creating wrapper classes (like this)?

class MyClassWrapper: Identifiable {
    let id = UUID()
    var myClass: MyClass
}

Upvotes: 2

Views: 1014

Answers (1)

jnpdx
jnpdx

Reputation: 52387

You can use an extension to conform to Identifiable in Swift -- then just specify which property should be used as the id:

//obj-c
@interface MyClass : NSObject
@property (strong,nonatomic) NSString* myIdProperty;
@end
//Swift
extension MyClass : Identifiable {
    public var id: String {
        myIdProperty
    }
}

I used NSString/String here, but you could use NSUUID/UUID or any other Hashable-conforming id type.

Upvotes: 8

Related Questions