How to create enum with raw type of CGPoint?

后端 未结 3 765
小蘑菇
小蘑菇 2020-12-13 09:59

Inspired from this question. Swift support to create enum with any raw type, so it will be nice to able to create enum with raw type of CGPoint.

But this code won\'t

3条回答
  •  旧时难觅i
    2020-12-13 10:27

    You can actually have a proper way. This is the code that allows you to have CGPoint as a RawValue of enum:

    enum MyPointEnum {
        case zero
    }
    
    extension MyPointEnum: RawRepresentable {
        typealias RawValue = CGPoint
    
        init?(rawValue: CGPoint) {
            if rawValue == CGPoint.zero {
                self = .zero
            } else {
                return nil
            }
        }
    
        var rawValue: CGPoint {
            switch self {
            case .zero:
                return CGPoint.zero
            }
        }
    }
    
    print(MyPointEnum.zero.rawValue) //prints "(0.0, 0.0)\n"
    

提交回复
热议问题