斯威夫特山地车_斯威夫特枚举

斯威夫特山地车

In this tutorial, we’ll be discussing the basics of Swift enum. You must be familiar with Enumerations if you have a previous programming background. Enumerations in Swift are really powerful and more awesome. Let’s dive right into them!

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

迅捷枚举 (Swift Enum)

As per the Apple Documentation: “An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code”.

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

In other words, Enumerations are lists of things. Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes such as defining functions within them.

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

Swift enum also allows us to define our own data types as well as handle various types of values. Let’s look at Swift enum syntax.

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

Swift枚举语法 (Swift Enum Syntax)

An enumeration is defined using the enum keyword followed by the name as shown below.

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

enum enumName {
   // Add values here
}

We can add different values inside the enum as shown below.

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

enum DaysOfAWeek{

    case Monday
    case Tuesday
    case Wednesday

}

The values inside an enumeration are defined using the keyword case. All such values are known as enumeration cases. Instead of defining every enumeration case separately, we can do it in a shorter way as shown below.

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

enum DaysOfAWeek{
    case Monday, Tuesday, Wednesday
}

Note: As per the guidelines, Swift Enum name and values should begin with a capital letter.

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

An enum value is specified to a variable in the following way:

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

var today = DaysOfAWeek.Monday

today = .Tuesday
today = .Wednesday

Once the value is defined you can reassign it without the need to specify enum name again.

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

Swift lets you auto-complete the value name from the list of cases defined.

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

在Swift枚举中使用switch语句 (Using switch statement with Swift enum)

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.
}

Note: default case in switch is not required since we’ve covered all the enum cases in the above code.

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

If some of the enum cases aren’t covered we’ll need a default for sure then as shown below:

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

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中的枚举内部函数 (Function inside an Enum in Swift)

We can define a function inside an enum in swift programming. Following is a function defined that sets the default Enum value as one of the cases:

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

enum DaysOfAWeek{

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

}

var today = DaysOfAWeek() //Sunday

枚举是值类型而不是引用类型 (Enums are value type and not reference type)

Enums values are passed by values. The following code demonstrates an example:

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

var today = DaysOfAWeek()

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

关联价值 (Associated Values)

Associated Values allows each case to have one or more types (e.g. Int, String, Double) that the enumeration cases can use.

关联值允许每种个案具有枚举个案可以使用的一种或多种类型(例如,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)

使用开关提取关联值 (Extracting associated values using 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

That’s pretty awesome! Using Enums we were able to reassign a variable to different types and extract the associated values each time.

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

用类型初始化枚举 (Initialising Enums With Types)

The Syntax to initialise an Enum with types is given below:

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

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"
  1. In the above code we’ve defined an enum with type String.

    在上面的代码中,我们定义了一个String类型的枚举。
  2. This allows us to assign a value to cases in the enum block itself rather than doing in switch statements like we did previously.

    这使我们能够为枚举块本身中的个案分配一个值,而不是像以前那样在switch语句中进行分配。
  3. These values assigned to cases are known as Raw Values which have the same type as that of Enum(String in above case).

    这些分配给案例的值称为原始值,其原始类型与Enum(以上案例中的String)的类型相同。
  4. These raw values can be returned when called upon the enum cases as DaysOfAWeek.Sunday.rawValue.

    在枚举实例中DaysOfAWeek.Sunday.rawValue时,可以返回这些原始值。
  5. A case which doesn’t have any Raw Value defined would consider the case name as the raw value.

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

Swift Enum Raw Values doesn’t exist when the enum type is not defined.

未定义枚举类型时,Swift Enum Raw Values不存在。

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

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

Let’s simplify the switch statement now that we have values stored as raw values:

现在,我们将值存储为原始值,以简化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
}

从枚举原始值检索枚举大小写 (Retrieve Enum case from Enum Raw Value)

The Enumeration case can be retrieved from the rawValue in the following manner.

枚举情况可以通过以下方式从rawValue中检索。

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

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

We pass the rawValue inside the DaysOfAWeek standard init and an optional is returned. Refer here on Optionals.

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

自动设置原始值 (Auto-set Raw Values)

Raw values can be auto-set for enum cases if it’s set for one case as shown below:

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

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

将枚举大小写转换为字符串 (Convert Enum case to String)

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 (Enum HashValue vs RawValue)

All enum cases have a hashValue which is like an index of the enum cases in the order in which they are defined. The index starts from 0. HashValue exists for enums with types and enums without types. On the other hand, rawValues are used to assign a value to enum cases. RawValues exists for enums with type only.

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

enum DaysOfAWeek{

case Sunday
case Monday
case Tuesday
case Wednesday
    
}

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

可选是枚举 (Optionals Are Enums)

Yes indeed. Let’s see why?
Swift Optionals are a type with two cases. Either the value exists or it doesn’t. If the value exists the Optional wraps the value as Optional(value).
Let’s see how an Int Optional looks like:

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

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

Essentially, an Optional is an Enum with two cases that we can define:

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

  • NoValue: When the value is not defined/nil

    NoValue :未定义/无值时
  • Value(Int): When the value is defined. We use the associated values with the enum case here.

    Value(Int) :定义值时。 在这里,我们将关联值与枚举大小写一起使用。

The code for OptionalInt in the form of Enums is given below:

下面以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)") 
}

That shows that Optionals are internally Enumerations.

这表明Optional是内部枚举。

This brings an end to Swift Enum tutorial.

这样就结束了Swift Enum教程。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/15343/swift-enum

斯威夫特山地车

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值