简体   繁体   中英

How do you cases in swift enumeration that has default values for some cases and dynamic values for others?

Lets take an example of enumeration of FileTypes

  enum FileType {
    case Header
    case Image
    case Swift
    init? (rawValue : String ){
        switch rawValue {
        case "h":
            self = .Header
        case "png" , "jpeg", "jpg":
            self = .Image
        case "swift":
            self = .Swift
        default:
            return nil
        }
    }
}

The above enumeration works fine for the statement

let fileType = FileType(rawValue:"jpeg")
let fileType2 = FileType(rawValue:"png")

Both fileType and fileType2 will resolve to .Image enumeration case. But when I access their rawValue, it will contain "Image".

How would I achieve to get the actual extension that got resolved to .Image at the first place? ie accessing

fileType.rawValue should result in jpeg

fileType2.rawValue should result in png .

You need to tell explicitly what the values will be.

enum FileType: String {
    case Header = "h"
    case Image = "jpg"
    case Swift = "swift"
}

This way you tell the enum is a string type.

EDIT: I forgot about the .Image case. I think you cannot have a case that have several different values. If you'd get a FileType(rawValue: "jpg") then you will get .Image, which is right. But what if you have .Image, how can Swift determine if it is "jpg" or "png"? That's the wrong approach.

Instead you could extend String, something like this:

extension String {
    var extensionIsImage: Bool {
        return self == "jpg" || self == "png"
    }
}

That way you wouldn't lose the value of the extension.

EDIT 2: Please note that extension String denotes a Swift extension, not the file extension.

This should give you a better idea of how to handle that type of situation:

enum FileType {
    case Header
    case Imge(String)
    case Swift
    init? (fileExt : String ){
        switch fileExt {
        case "h":
            self = .Header
        case "png" , "jpeg", "jpg":
            self = .Imge(fileExt)
        case "swift":
            self = .Swift
        default:
            return nil
        }
    }
}

var fileType = FileType(fileExt:"jpeg")!
var fileType2 = FileType(fileExt:"png")!

switch fileType2 {
case let .Imge(exten):
    print("\(exten)", terminator:"")
default:
    print("Error")
}

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