Objective-C中的通用枚举类型

时间:2019-04-30 22:14:13

标签: ios objective-c swift enums

我有两个Objective-c类HondaDealerShipFordDealerShip。它们都包含相似的属性和方法,因此我想定义一个通用协议DealerShip并进行一些多态处理。

问题在于,DealerShip需要包含通用的枚举类型属性,以便HondaDealerShipFordDealerShip可以具有不同的concrete枚举类型。

所以我想要这样的东西,

@protocol DealerShip 

@property (nonatomic, readonly) enum location;

-(void)printPriceOfModel:(enum)vehicleModel;

@end
typedef NS_ENUM(NSInteger, HondaLocation) {
     HondaLocationSouthEast,
     HondaLocationNorthWest
}

typedef NS_ENUM(NSInteger, HondaModel) {
     Accord,
     Civic
}

@interface HondaDealerShip: NSObject<DealerShip>

@property (nonatomic, readonly) HondaLocation location;

- (void)printPriceOfModel:(HondaModel)vehicleModel {
     //print price here
}

@end
typedef NS_ENUM(NSInteger, FordLocation) {
     FordLocationEast,
     FordLocationWest
}

typedef NS_ENUM(NSInteger, FordModel) {
     Mustang,
     Focus
}

@interface FordDealerShip: NSObject<DealerShip>

@property (nonatomic, readonly) FordLocation location;

- (void)printPriceOfModel:(FordModel)vehicleModel {
     //print price here
}

@end

如果必须在swift中执行此操作,则可以使用具有以下关联类型的协议

protocol DealerShip {
    associatedtype Location
    associatedtype Model

    var location: Location { get }
    func printPriceOfModel(model : Model)
}

enum HondaLocation: Int {
    case sountEast
    case northWest
}

enum HondaModel: Int {
    case accord
    case civic
}

struct HondaDealerShip: DealerShip {
    var location: HondaLocation
    func printPriceOfModel(model: HondaModel) {
        //print
    }
}

//same for FordDealerShip

我可以在Objective-c中做类似的事情吗?

1 个答案:

答案 0 :(得分:0)

不,您不能在目标c中使用带有关联类型的枚举。该语言不支持。