■enum
基本的な定義の仕方
//定義の仕方
enum BloodType {
case a
case b
case o
case ab
}
基本的な使い方
switch文を使う。
if文でも出来るがswitchの方がいい
switchなら定義する時enumの全てのcaseが入っていなければエラーになるので。
抜けていれば教えてくれる。
let type = BloodType.a
switch type {
case .a:
print("血液型A型")
case .b:
print("血液型b型")
default:
print("血液型それ以外")
}
■値を持たせることもできる。型を指定できる。文字型,整数,浮動小数のみ
enum Color: Int {
case red = 0
case blue = 1
case green = 2
}
//省略してかける。
//インクリメントで値が代入される。
enum Color2: Int {
case red = 5, blue,green
}
//定義の方法
let color1 = Color.red
let color2: Color = .green
//rawValueで値を指定してアクセスできるがoptinalになる。
let color3 = Color.init(rawValue: 2)
//rawValueで値にアクセスできる。
print("\(color1),\(color1.rawValue)")
//結果: red 0
print("\(color2),\(color2.rawValue)")
//結果 blue 1
print("\(color3),\(color3?.rawValue)")
//結果 Optional(__lldb_expr_2.Color.green),Optional(2)
■enumパラメーターを持たせれる。
enum Country {
case japan(String,Int)
case america(String,Int)
case antarctic(Int)
}
let country1 = Country.japan("日本語",300)
let country2 = Country.america("英語", 500)
let country3 = Country.antarctic(0)
switch country1 {
case .japan(let lang, let num):
print("日本:\(lang),\(num)人")
case .america(let lang, let num):
print("アメリカ : \(lang, \(num))")
case .antarctic(let num):
print("南極 : \(num)人")
}
//結果 日本: 日本語, 300人
■caseだけでなく変数や関数も入れる事ができる。
enum Test: Int {
case one = 1, two, three
var aaa: Int {
return self.rawValue * 10
}
func bbb()-> String {
switch self {
case .one: return "Oneは1"
case .two: return "Twoは2"
case .three: return "Threeは3"
}
}
}
let testThree = Test.three
print("\(testThree)") // three
print("\(testThree.aaa)") // 30
print("\(testThree.bbb)") //Threeは3
このパターンをよく使うらしい
後は慣れていきます!!