Sam Sam - 6 months ago 12
Swift Question

Conforming to an Obj-C protocol's property in Swift

I'm implementing a protocol from an Obj-C library in a Swift class that defines two properties as:

@property (nonatomic, assign, getter = isLoading) BOOL loading;
@property (nonatomic, readonly) UIExpansionStyle expansionStyle;


Although I'm not sure how to conform to these requirements in my Swift class.

I've looked at the Obj-C examples, but I haven't gleaned any solutions from that. I've tried declaring class variables with the same name, but that hasn't worked. Any suggestions on how I would go about this?

PS, the library in question is https://github.com/OliverLetterer/SLExpandableTableView

Answer

I think you're making this harder than it needs to be. With a protocol defined like this:

@protocol MyProtocol

@property (nonatomic, assign, getter = isLoading) BOOL loading;
@property (nonatomic, readonly) UIExpansionStyle expansionStyle;

@end

the following class conforms:

class Conformer : MyProtocol {
    var loading: Bool
    var expansionStyle: UIExpansionStyle

    init(loading: Bool, expansionStyle: UIExpansionStyle) {
        self.loading = loading
        self.expansionStyle = expansionStyle
    }
}

Prefixing boolean getters with is is a Cocoa convention, so Swift already knows about it and doesn't require you to do anything special on the swift side.

The confusing part might be all the modifiers to the Objective C property declaration. Let's go through them one by one.

nonatomic has no equivalent in Swift, nothing to do here.

assign is automatic for value types, nothing to do here either.

getter = isLoading is a Cocoa convention which Swift understands and needs nothing from you in order to make this work.

readonly you can do this in Swift (just use the get{ } syntax) but it is not necessary. This is because you are allowed to expand on the contract made by the protocol. MyProtocol requires there be a property called expansionStyle that can be read from, it does NOT say that it must not be possible to write to that property in the type that implements the protocol, just like it doesn't say you can't have other properties/methods on that same class.

Comments