最近在看一个第三方SDK提供的demo代码,写法如下:
那种写法看着像枚举,但是确实不是枚举,为什么作者要这么写呢?
当时没有理解,后来终于体会到了
其实,这个是因为SDK想使用swift字符串枚举,但是呢 OC不支持,
想要保留swift的代码风格同时兼容OC,无奈使用这种脱裤子放屁的写法 😂
同样道理,例如我想要使用swift 字符串类型枚举,如果是纯swift项目,我们可以这样写:
enum QYDataMimeType: String {
case JPEG = "image/jpeg"
case PNG = "image/png"
case GIF = "image/gif"
case HEIC = "image/heic"
case HEIF = "image/heif"
case WEBP = "image/webp"
case TIF = "image/tif"
case JSON = "application/json"
}
但是为了同时兼容Objective-C ,但又想保留swift的风格只能写成这样
/// 常见数据类型的`MIME Type
@objc
final class QYDataMimeType: NSObject {
typealias QYDataMimeType = NSString
@objc static let JPEG: QYDataMimeType = "image/jpeg"
@objc static let PNG: QYDataMimeType = "image/png"
@objc static let GIF: QYDataMimeType = "image/gif"
@objc static let HEIC: QYDataMimeType = "image/heic"
@objc static let HEIF: QYDataMimeType = "image/heif"
@objc static let WEBP: QYDataMimeType = "image/webp"
@objc static let TIF: QYDataMimeType = "image/tif"
@objc static let JSON: QYDataMimeType = "application/json"
// 某些地方需要传入字符串,QYDataMimeType 转 NSString 防止编译器警告
@objc func stringValue() -> NSString {
return String(describing:self ) as NSString
}
}