【发布时间】:2019-04-30 22:14:13
【问题描述】:
我有两个objective-c 类HondaDealerShip 和FordDealerShip。它们都包含相似的属性和方法,所以我想定义一个通用协议DealerShip 并做一些多态性。
问题是这个DealerShip需要包含通用枚举类型属性,这样HondaDealerShip和FordDealerShip可以有不同的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 中做类似的事情吗?
【问题讨论】:
标签: ios objective-c swift enums