Swift枚举

时间:2020-02-23 14:44:00  来源:igfitidea点击:

在本教程中,我们将讨论Swift枚举的基础。
如果您具有以前的编程背景,则必须熟悉枚举。
Swift中的枚举功能非常强大且更加出色。
让我们直接深入其中!

Swift枚举

根据Apple文档:"枚举为一组相关值定义了通用类型,并使您能够在代码中以类型安全的方式使用这些值"。

换句话说,枚举是事物的列表。
Swift中的枚举本身就是一流的类型。
它们采用了传统上仅由类支持的许多功能,例如其中定义功能。

Swift枚举还允许我们定义自己的数据类型以及处理各种类型的值。
让我们看一下Swift枚举语法。

Swift枚举语法

使用关键字enum定义枚举,后跟名称,如下所示。

enum enumName {
 //Add values here
}

我们可以在枚举内添加不同的值,如下所示。

enum DaysOfAWeek{

  case Monday
  case Tuesday
  case Wednesday

}

枚举中的值是使用关键字" case"定义的。
所有这些值都称为枚举情况。
除了可以单独定义每个枚举用例之外,我们还可以用更短的方式进行操作,如下所示。

enum DaysOfAWeek{
  case Monday, Tuesday, Wednesday
}

注意:根据准则,Swift Enum名称和值应以大写字母开头。

枚举值通过以下方式指定给变量:

var today = DaysOfAWeek.Monday

today = .Tuesday
today = .Wednesday

定义值后,您可以重新分配它,而无需再次指定枚举名称。

Swift可让您从定义的案例列表中自动填写值名称。

在Swift枚举中使用switch语句

var today = DaysOfAWeek.Monday
today = .Wednesday

switch today {
case .Monday: print("Today is Monday")
case .Tuesday: print("Today is Tuesday")
case .Wednesday: print("Today is Wednesday") //this gets printed.
}

注意:因为我们已经在上面的代码中介绍了所有枚举情况,所以不需要在切换时使用默认大小写。

如果某些枚举案例没有涵盖,我们肯定需要一个默认值,如下所示:

var today = DaysOfAWeek.Monday
today = .Wednesday

switch today {
case .Monday: print("Today is Monday")
case .Tuesday: print("Today is Tuesday")
default: print("Today is neither Monday nor Tuesday") //this gets printed.
}

在Swift中的枚举内部函数

我们可以在快速编程中的枚举内定义一个函数。
以下是定义了将默认Enum值设置为以下情况之一的函数:

enum DaysOfAWeek{

  case Sunday
  case Monday
  case Tuesday
  case Wednesday
  
  init() {
    self = .Sunday
  }

}

var today = DaysOfAWeek() //Sunday

枚举是值类型而不是引用类型

枚举值通过值传递。
以下代码演示了一个示例:

var today = DaysOfAWeek()

var anotherDay = today //Sunday
anotherDay = .Monday //Monday

关联值

关联值允许每种个案具有枚举个案可以使用的一种或者多种类型(例如,Int,String,Double)。

enum ValuesOfDifferentType{

  case Str(String)
  case Inte(Int)
  case Numb(Double)
  case LatLng(Double, Double)
  case Boo(Bool)
  
  init(){
  self = .Str("Hello World")
  
  }
}

var values = ValuesOfDifferentType() //returns Str("Hello World")
values = .Inte(10) //returns Inte(10)
values = .Boo(true) //returns Boo(true)

使用switch提取关联值

func runSwitch(with value: ValuesOfDifferentType)
{
switch value {
case .Str(let str): print("String value is \(str)")
case .Inte(let i) : print("Integer value is \(i)")
case .Numb(let d) : print("Double value is \(d)")
case .LatLng(let lat, let lng): print ("Lat \(lat) and Lng \(lng)")
case .Boo(let b) : print("Boolean value is \(b)")

}

}

runSwitch(with: values) //prints String value is Hello World

values = .Inte(10) 
runSwitch(with: values)//prints Integer value is 10

values = .Numb(12.23)
runSwitch(with: values)//prints Double value is 12.23

values = .LatLng(26.213, 75.4343)
runSwitch(with: values)//prints Lat 26.213 and Lng 75.4343

values = .Boo(false)
runSwitch(with: values)//prints Boolean value is false

使用枚举,我们能够将变量重新分配给不同的类型,并每次提取关联的值。

用类型初始化枚举

下面给出初始化带有类型的枚举的语法:

enum DaysOfAWeek : String{

case Sunday = "Today is Sunday"
case Monday = "Today is Monday"
case Tuesday = "Today is Tuesday"
case Wednesday

}

var today = DaysOfAWeek.Sunday.rawValue //returns "Today is Sunday"
today = DaysOfAWeek.Wednesday.rawValue //retuns "Wednesday"
  • 在上面的代码中,我们定义了一个String类型的枚举。

  • 这使我们能够为枚举块本身中的个案分配一个值,而不是像以前那样在switch语句中进行分配。

  • 这些分配给案例的值称为原始值,其原始类型与Enum(上述案例中的String)的类型相同。

  • 在枚举用例中以DaysOfAWeek.Sunday.rawValue的形式调用时,可以返回这些原始值。

  • 没有定义任何原始值的案例会将案例名称视为原始值。

未定义枚举类型时,Swift枚举原始值不存在。

enum DaysOfAWeek{
case Sunday = "Today is Sunday" //Compile-time Error
case Wednesday
}

var today = DaysOfAWeek.Sunday.rawValue //error. rawValue method not found.

现在,我们将值存储为原始值,以简化switch语句:

enum DaysOfAWeek: String{

case Sunday = "Today is Sunday"
case Monday = "Today is Monday"
case Tuesday = "Today is Tuesday"
case Wednesday = "Today is Wednesday"

}

var day = DaysOfAWeek.Wednesday

switch day {
case .Sunday, .Monday, .Tuesday, .Wednesday: print(day.rawValue) //prints Today is Wednesday
}

从枚举原始值检索枚举大小写

枚举的情况可以通过以下方式从" rawValue"中获取。

var possibleDay = DaysOfAWeek(rawValue: "Today is Monday")
print(possibleDay ?? "Day doesn't exist")

possibleDay = DaysOfAWeek(rawValue: "Thursday")
print(possibleDay ?? "Day doesn't exist")

我们在DaysOfAWeek标准init内部传递rawValue,并返回一个可选值。
请参阅此处的可选。

自动设置原始值

如果为一种情况设置原始值,则可以为枚举情况自动设置原始值,如下所示:

enum Numbers :Int{

  case caseOne = 100, caseTwo
  case caseThree

}

var num = Numbers.caseOne.rawValue //prints 100
num = Numbers.caseTwo.rawValue //prints 101
num = Numbers.caseThree.rawValue //prints 102

enum Numbers :Int{

  case caseOne, caseTwo = 2
  case caseThree

}

var num = Numbers.caseOne.rawValue //prints 1
num = Numbers.caseTwo.rawValue //prints 2
num = Numbers.caseThree.rawValue //prints 3

enum Numbers :Int{

  case caseOne = 100, caseTwo = 2
  case caseThree

}

var num = Numbers.caseOne.rawValue //prints 100
num = Numbers.caseTwo.rawValue //prints 2
num = Numbers.caseThree.rawValue //prints 3

将枚举大小写转换为字符串

enum DaysOfAWeek: String{

case Sunday
case Monday
case Tuesday
case Wednesday

  func day()->String{
  
      return self.rawValue
  
  }
  
}

var str = DaysOfAWeek.Sunday.day() //returns "Sunday" as a string.

枚举HashValue与RawValue

所有枚举案例都有一个" hashValue",这类似于按定义顺序列出的枚举案例的索引。
索引从0开始。
HashValue用于具有类型的枚举和不具有类型的枚举。
另一方面,rawValues用于为枚举案例分配一个值。
RawValues仅适用于类型为枚举的枚举。

enum DaysOfAWeek{

case Sunday
case Monday
case Tuesday
case Wednesday
  
}

var day = DaysOfAWeek.Wednesday
day.hashValue //returns 3

可选是枚举

确实是的。
让我们看看为什么? Swift Optionals是一种有两种情况的类型。
该值存在或者不存在。
如果值存在,则Optional将值包装为Optional(value)。
让我们看看Int Optional的样子:

var optionalVariable: Int? = 5 //Case when value does exist.
optionalVariable = nil //Case when value doesn't exist.

本质上,一个Optional是一个Enum,其中可以定义两种情况:

  • NoValue:未定义/无值时
  • Value(Int):定义值时。
    其中我们将关联值与枚举大小写一起使用。

下面以Enums形式给出OptionalInt的代码:

enum OptionalInt{

  case NoValue
  case Value(Int)

}

var optionalInt : OptionalInt = .Value(5)

switch optionalInt {
case .NoValue: print("Optional doesn't contain any value")
case .Value(let value):  print("Optional value is \(value)") //prints "Optional value is 5\n"
}

optionalInt = .NoValue

switch optionalInt {
case .NoValue: print("Optional doesn't contain any value") //This is printed
case .Value(let value):  print("Optional value is \(value)") 
}

这表明Optional是内部枚举。