oc 中用swift中枚举_Swift中的枚举,元组和泛型

oc 中用swift中枚举

A brief discussion on how to uses enum, generics, and tuples in the Swift programming language.

简要讨论如何在Swift编程语言中使用枚举,泛型和元组。

总览 (Overview)

Like other programming languages, Swift also has special features like enum, tuples, and generics. They have different use cases depending upon different conditions. In this tutorial, we will learn

与其他编程语言一样,Swift也具有特殊功能,例如枚举,元组和泛型。 根据不同的条件,它们具有不同的用例。 在本教程中,我们将学习

What, when, and how to use enumerations, tuples, and generics in Swift? So let’s get started

在Swift中什么使用,何时使用以及如何使用枚举元组和泛型 ? 所以我们开始吧

This tutorial is written using Swift 5 and Xcode 11.4.1.

本教程使用 Swift 5和Xcode 11.4.1 编写

1.枚举 (1. Enumerations)

According to swift 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.”

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

  • Creating an enum: You can declare an enum like this in swift

    创建一个枚举:您可以Swift声明一个枚举

enum TimePeriod{
           case morning
case noon
case afternoon
case night
}

Where the name of this enum is “TimePeriod” and it has four cases as “morning”, “noon”, “afternoon” and “night”.

该枚举的名称为“ TimePeriod”,它具有“早晨”,“中午”,“下午”和“晚上”四种情况。

We also can declare the cases in a single line like this

我们也可以像这样单行声明案例

enum TimePeriod{
       
case morning, noon, afternoon, night
}
  • enum type: When we define an enum itself define a new type in swift. We can define a variable as this type

    枚举类型:当我们定义枚举本身时,Swift定义一个新类型。 我们可以定义一个变量作为这种类型

var presentTime = TimePeriod.morning
print(presentTime) // morning

“presentTime” variable is “TimePeriod” enum type and its value is “morning”

“ presentTime”变量是“ TimePeriod”枚举类型,其值是“ morning”

Once it defined that “presentTime” is “TimePeriod” type we can set others value of enum using “.” operation

一旦定义了“ presentTime”为“ TimePeriod”类型,我们就可以使用“。”设置其他枚举值。 操作

presentTime = .noon
presentTime = .afternoon
presentTime = .night
  • Matching enum value: Swift switch statement is a simple and straight forward solution for matching the enum value.

    匹配枚举值: Swift switch语句是一种简单而直接的解决方案,用于匹配枚举值。

switch presentTime {case .morning:
print("Foggy morning
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值