user5812721 user5812721 - 5 months ago 15
Swift Question

"Use of unresolved identifier" error, yet I have the identifier declared in a framework

The errors come up in this method:

func stringFromProduct(product: SPTProduct) -> String {
switch product {
case SPTProductFree:
return "Free"
case SPTProductPremium:
return "Premium"
case SPTProductUnlimited:
return "Unlimited"
default:
return "Unknown"
}
}


They show up at SPTProductFree, SPTProductPremium, and SPTProductUnlimited.

Yet, in a header file of a framework I am using, this is declared:

typedef NS_ENUM(NSUInteger, SPTProduct) {
SPTProductFree,
SPTProductUnlimited,
SPTProductPremium,
SPTProductUnknown
};


My bridging file is set up correctly, but it still says it is an unresolved identifier.

Thanks!

Answer

From Interacting with C APIs in the "Using Swift with Cocoa and Objective-C" reference:

Swift imports any C enumeration marked with the NS_ENUM macro as a Swift enumeration with an Int raw value type. The prefixes to C enumeration case names are removed when they are imported into Swift, whether they’re defined in system frameworks or in custom code.

So your Objective-C enumeration is imported to Swift as

public enum SPTProduct : UInt {
    case Free
    case Unlimited
    case Premium
    case Unknown
}

and you can see that by using the "Generated Interface" menu item on the Objective-C header file containing the definition.

Consequently, you use it from Swift as

func stringFromProduct(product: SPTProduct) -> String {
    switch product {
    case .Free:
        return "Free"
    case .Premium:
        return "Premium"
    case .Unlimited:
        return "Unlimited"
    default:
        return "Unknown"
    }
}