LoginSignup
4
5

More than 5 years have passed since last update.

Swift 列挙型について(Associated Value、Raw Value)

Last updated at Posted at 2016-03-11

列挙型について記載します

まとめて宣言するケース

enum Planet {
    case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

enumに関数をもたせたケース

enum Animals:String{
    case Rion = "rion"
    case Cat = "cat"
    case Dog = "dog"
    case Panda = "panda"

    func description() -> String {
        switch self {
            case .Rion:
                return "description rion"
            case .Cat:
                return "description cat"
            case .Dog:
                return "description dog"
            case .Panda:
                return "description panda"
        }
    }
}
Animals.Rion.description()  //description rion

Associated Values
特定の型を指定したいが、別の型で置き換えたい時もある場合に使用

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)

    func traceValue() ->Void {
        switch self {
        case .UPCA(let numberSystem, let manufacturer, let product, let check):
            print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
        case .QRCode(let productCode):
            print("QR code: \(productCode).")
        }
    }
}

var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode.traceValue()   //UPCA(8, 85909, 51226, 3)

productBarcode = .QRCode("ABCDEF")
productBarcode.traceValue()  //QRCode("ABCDEF")

全てのassociated valuesを変数や、定数で指定する場合は以下のように記載

switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
    print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
    print("QR code: \(productCode).")
}

Raw Values
全て同じ型を持った列挙型がRaw Valuesになります
Raw Valueの取り出しはrawValueプロパティでアクセスします

enum ColorsImage:String {
    case red = "hot"
    case blue = "cool"
    case yellow = "pretty"
}
let colorImage = ColorsImage.red.rawValue
print(colorImage) //hot

同じRaw Value を指定するとエラーになります

enum ColorsImage:String {
    case red = "hot"
    case blue = "cool"
    case yellow = "pretty"
    case grey = "cool"  //error
}

自動でRaw Valueがセットされる例

enum Planet: Int {
    case Mercury = 3, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Planet.Mercury.rawValue //3
Planet.Venus.rawValue //4

以上

参考:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5