简体   繁体   中英

Can I extend the Swift reserved word “enum”?

For example, I want to add something like this:

extension enum : T {
    convenience init? (rawData: T?) -> enum? {
        guard let rawData = rawData else { return nil; }
        return self.init(rawData: rawData);
    }
}

I know this is probably not a best case of why I need to extend the enum, but I just want to explore the possibilities. Thanks.

From Extensions in “The Swift Programming Language” (emphasis added):

Extensions add new functionality to an existing class, structure, enumeration, or protocol type.

enum is a keyword, not a type, therefore an extension enum cannot be defined.

If your intention is to instantiate an enumeration value from an optional raw value, then you can define a “protocol extension” :

extension RawRepresentable {
    init?(rawData: RawValue?) {
        guard let rawData = rawData else { return nil }
        self.init(rawValue: rawData)
    }
}

This adds a new initializer to all types conforming to the RawRepresentable protocol, in particular to all enumeration types with a raw value type.

Example:

enum Foo: String {
    case a
    case b
}

print(Foo(rawData: "a"))  // Optional(Foo.a)
print(Foo(rawData: "x"))  // nil
print(Foo(rawData: nil))  // nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM