斯威夫特山地车

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 Mondaycase Tuesdaycase 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.Mondaytoday = .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 = .Wednesdayswitch 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 = .Wednesdayswitch 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 Sundaycase Mondaycase Tuesdaycase Wednesdayinit() {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 Worldvalues = .Inte(10)
runSwitch(with: values)//prints Integer value is 10values = .Numb(12.23)
runSwitch(with: values)//prints Double value is 12.23values = .LatLng(26.213, 75.4343)
runSwitch(with: values)//prints Lat 26.213 and Lng 75.4343values = .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.Wednesdayswitch 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, caseTwocase caseThree}var num = Numbers.caseOne.rawValue //prints 100
num = Numbers.caseTwo.rawValue //prints 101
num = Numbers.caseThree.rawValue //prints 102enum Numbers :Int{case caseOne, caseTwo = 2case caseThree}var num = Numbers.caseOne.rawValue //prints 1
num = Numbers.caseTwo.rawValue //prints 2
num = Numbers.caseThree.rawValue //prints 3enum Numbers :Int{case caseOne = 100, caseTwo = 2case 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 Wednesdayfunc 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/nilNoValue :未定义/无值时
  • 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 NoValuecase 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 = .NoValueswitch 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

斯威夫特山地车

斯威夫特山地车_斯威夫特枚举相关推荐

  1. 斯威夫特山地车_斯威夫特| 两个数字相加的程序

    斯威夫特山地车 In this program, we will have an idea - how two numbers can be added and displayed as the ou ...

  2. 斯威夫特山地车_斯威夫特弦乐

    斯威夫特山地车 Today we will look into Swift String operations. Furthermore, we'll be discussing the change ...

  3. 斯威夫特山地车_斯威夫特字典

    斯威夫特山地车 Swift Dictionary is one of the important collection types. Let's get started by launching th ...

  4. java 枚举值属性_获取枚举值的属性

    我想知道是否可以获取枚举值而不是枚举本身的属性? 例如,假设我有以下枚举: using System.ComponentModel; // for DescriptionAttribute enum ...

  5. 注解代替枚举_精选枚举代替开关

    注解代替枚举 问题及其解决方案 开关/案例是用大多数命令式编程语言实现的通用控制结构. 开关比一系列的if / else更具可读性. 这是一个简单的示例: // Switch with int lit ...

  6. 扩展方法 枚举值_扩展枚举功能的两种方法

    扩展方法 枚举值 前言 在上一篇文章中,我解释了如何以及为什么在Java代码中使用enums而不是switch/case控制结构. 在这里,我将展示如何扩展现有enums功能. 介绍 Java enu ...

  7. 幼儿园买玩具_二进制枚举

    . 幼儿园买玩具 蒜厂幼儿园有 nn 个小朋友,每个小朋友都有自己想玩的玩具.身为幼儿园园长的你决定给幼儿园买一批玩具,由于经费有限,你只能买 mm 个玩具.已知玩具商店一共卖 kk 种玩具,编号为 ...

  8. ios 结构体跟枚举变量的区别_[Swift]枚举、类与结构体的对比

    ###枚举.类与结构体的对比### ####枚举与其他两者的关系#### 首先说枚举,相对比较好区分,因为我们知道,枚举与其他两者最大的相同之处就在于都可以定义方法. 而其他的更多特性,对于枚举基本没 ...

  9. python枚举算法流程图_算法-枚举

    本章我们进入算法的学习,我们会通过比较经典的例题去讲解一些常用的算法思想,常用的算法思想包括:枚举.递归.分治.贪心.试探.动态迭代和模拟等,本节我们来学习一下枚举算法. 1. 枚举思想 枚举算法我们 ...

最新文章

  1. 伪元素first-letter
  2. 计算机什么时候学汇编,[计算机基础] 汇编学习(1)
  3. xshell如何登陆堡垒机_Xshell连接有跳板机(堡垒机)的服务器
  4. SQL Server 创建数据库快照
  5. 龙岗网络推广浅析更新频率对网站优化有哪些影响?
  6. UVA12299 线段树水水水,但别乱开空间= =
  7. 深入理解分布式技术 - 服务注册与发现背后的逻辑
  8. docker新建Linux虚拟机,RHEL/CentOS 7下创建你的第一个Docker容器
  9. python代码有时候在命令行下和Python Shell中执行的结果不一样?
  10. python调用java方法_python调用java
  11. 衔接上一学期:排球积分规则
  12. 玩转mini2440开发板之【编译烧录rootfs根文件系统全过程记录】
  13. html中加入scrip代码,HTML script 标签 | 菜鸟教程
  14. 光标是停在文本框文字的最后
  15. 天下无贼中经典的句子
  16. Docker教程小白实操入门(21)--如何备份、恢复数据卷
  17. 从初级到资深:程序员的职业生涯思考与可迁移技能培养
  18. NETDMIS5.0边界点检测2023
  19. 基于Web SCADA平台构建实时数字化产线 - 初篇
  20. Linux 绑定IP

热门文章

  1. WDK10+VS2015 驱动环境搭建
  2. 软件开发实践的24条军规
  3. C Coding Standard
  4. (转)Mahout Kmeans Clustering 学习
  5. 【SPS2010】现在的这个版本不值得测试。
  6. [转载] Python全栈(1)—— Python如何快速下载库与jupyter notebook 的基本使用
  7. 用MySQLdb操作数据库流程示例:
  8. [转载]生活在 Emacs 中
  9. ubuntu 環境下 bochs 的安裝
  10. Select2 鼠标点击空白处不消失简单测试和解决方法