成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Swift 枚舉類型,你知道幾個?

開發 前端
本文我們介紹了在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關聯值等相關的內容。通過與 TypeScript 語法的對比,希望能幫助您更好地理解 Swift 的相關特性。

本文我們將介紹在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關聯值等相關的內容。如果你尚未安裝 Xcode 和配置 Swift 開發環境,請您先閱讀這篇文章。

接下來,我們啟動 Xcode,然后選擇 "File" > "New" > "Playground"。創建一個新的 Playground 并命名為 "Enumerations"。

在 Swift 中,枚舉(Enum)是一種特殊的數據類型,它允許你定義一組相關的值。這些值是你在程序中會用到的一些具體選項。

定義一個枚舉

在 Swift 中,我們使用 enum 關鍵字定義一個枚舉,在枚舉體內使用 case 關鍵字定義不同的情況,每個情況表示枚舉的一個成員。

Swift Code

enum Color {
    case red
    case green
    case blue
}

let greenColor = Color.green

print(greenColor)
// Output: green

在以上代碼中,我們定義了一個名為 Color 的枚舉,包含了三種顏色。

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

let color: Color = Color.Green;

console.log(color);
// Output: 1

使用 switch 處理枚舉

有了 Color 枚舉后,我們可以使用 switch 語句來處理枚舉。

Swift Code

enum Color {
    case red
    case green
    case blue
}

func describeColor(color: Color) {
    switch color {
    case .red:
        print("Color is red.")
    case .green:
        print("Color is green.")
    case .blue:
        print("Color is blue.")
    }
}

describeColor(color: .blue)

// Output: Color is blue.

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

function describeColor(color: Color): void {
    switch (color) {
        case Color.Red:
            console.log("Color is red.");
            break;
        case Color.Green:
            console.log("Color is green.");
            break;
        case Color.Blue:
            console.log("Color is blue.");
            break;
    }
}

describeColor(Color.Blue);

// Output: "Color is blue."

遍歷枚舉的成員

在 Swift 中,我們可以使用 CaseIterable 協議來使枚舉遵循可迭代的協議,從而實現對枚舉成員的遍歷。

Swift Code

enum Color: CaseIterable {
    case red, green, blue
}

for color in Color.allCases {
    print(color)
}

/**
Output: 
red
green
blue
*/

在上面的代碼中,我們讓 Color 枚舉遵循 CaseIterable 協議,以便枚舉該枚舉的所有成員。

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

for(let colorKey in Color) {
    console.log(colorKey)
}

/**
Output: 
"0" 
"1" 
"2" 
"Red" 
"Green" 
"Blue" 
*/

枚舉原始值

Swift 中的枚舉可以關聯原始值,這些原始值可以是整數、浮點數、字符串等類型。枚舉的原始值為每個成員提供了一個默認值,方便我們在不同的上下文中使用。

數值原始值

Swift Code

enum Weekday: Int {
    case sunday = 1
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
    case saturday
}

let today: Weekday = .tuesday
let rawValue: Int = today.rawValue

print(rawValue)
// Output: 3

在以上代碼中,我們定義了一個表示星期的枚舉 Weekday,并為每個成員顯式賦予了一個原始值。默認情況下,第一個成員的原始值為 1,后續成員的原始值遞增。

TypeScript Code

enum Weekday {
    Sunday = 1,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

let today: Weekday = Weekday.Tuesday;
let rawValue: number = today;

console.log(rawValue);
// Output: 3

在 TypeScript 中,數值枚舉的原始值也是遞增的,與 Swift 中的數值枚舉相似。

字符串原始值

Swift Code

enum Direction: String {
    case up = "UP"
    case down = "DOWN"
    case left = "LEFT"
    case right = "RIGHT"
}

let move: Direction = .up
let directionString: String = move.rawValue

print(directionString)
// Output: UP

在以上代碼中,我們定義了一個字符串枚舉 Direction,為每個成員顯式賦予了一個字符串原始值。

TypeScript Code

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT"
}

let move: Direction = Direction.Up;
let directionString: string = move;

console.log(directionString);
// Output: "UP"

字符串枚舉的原始值在 TypeScript 中也是類似的,允許為每個成員指定字符串類型的原始值。

枚舉關聯值

Swift 中的枚舉不僅可以有原始值,還可以攜帶關聯值。關聯值允許在定義枚舉的時候指定每個成員攜帶的數據類型。這樣,每個枚舉成員都可以攜帶不同類型的數據。

Swift Code

import Foundation

// 定義 Shape 枚舉描述不同的圖形
enum Shape {
    case circle(radius: Double)
    case square(side: Double)
    case rectangle(width: Double, height: Double)
}

// 使用關聯值創建不同的圖形
let circle: Shape = .circle(radius: 3.0)
let square: Shape = .square(side: 4.0)
let rectangle: Shape = .rectangle(width: 3.0, height: 4.0)

在以上代碼中,我們定義了一個 Shape 枚舉,其中的每個成員都可以攜帶不同類型的關聯值,表示不同的圖形。有了 Shape 枚舉之后,我們可以創建一個 calculateArea 函數,來計算不同圖形的面積。

Swift Code

func calculateArea(shape: Shape) -> Double {
    switch shape {
    case .circle(let radius):
        return Double.pi * pow(radius, 2)
    case .square(let side):
        return pow(side, 2)
    case .rectangle(let width, let height):
        return width * height
    }
}

// 計算不同圖形的面積
let areaOfCircle = calculateArea(shape: circle) // 28.27433388230814
let areaOfSquare = calculateArea(shape: square) // 16
let areaOfRectangle = calculateArea(shape: rectangle) // 12

在以上代碼中,我們定義了一個函數 calculateArea,根據圖形的類型計算圖形的面積。通過關聯值,我們可以輕松地提取不同圖形的屬性進行計算。在 TypeScript 中,由于并沒有直接對應 Swift 枚舉關聯值的語法,我們可以使用 TypeScript 的聯合類型來模擬這種行為。

TypeScript Code

interface Circle {
    kind: 'circle';
    radius: number;
}

interface Square {
    kind: 'square';
    side: number;
}

interface Rectangle {
    kind: 'rectangle';
    width: number;
    height: number;
}

// 使用聯合類型表示不同的圖形
type Shape = Circle | Square | Rectangle;

在以上代碼中,我們使用接口和聯合類型來定義不同圖形的數據結構。之后,我們也可以定義一個 calculateArea 函數來計算不同圖形的面積。

TypeScript Code

function calculateArea(shape: Shape): number {
    switch (shape.kind) {
        case 'circle':
            return Math.PI * Math.pow(shape.radius, 2);
        case 'square':
            return Math.pow(shape.side, 2);
        case 'rectangle':
            return shape.width * shape.height;
        default:
            throw new Error('Invalid shape');
    }
}

const circle: Circle = { kind: "circle", radius: 3.0 }
const square: Square = { kind: "square", side: 4.0 }
const rectangle: Rectangle = { kind: "rectangle", width: 3.0, height: 4.0 }

// 計算不同圖形的面積
const areaOfCircle = calculateArea(circle); // 28.274333882308138
const areaOfSquare = calculateArea(square); // 16
const areaOfRectangle = calculateArea(rectangle); // 12

枚舉中定義計算屬性

Swift Code

enum Color {
    case red, green, blue

    var hexValue: String {
        switch self {
        case .red:
            return "#FF0000"
        case .green:
            return "#00FF00"
        case .blue:
            return "#0000FF"
        }
    }
}

let greenColor = Color.green

print(greenColor.hexValue)
// Output: #00FF00

在以上代碼中,我們為 Color 枚舉增加了一個計算屬性 hexValue,用于表示顏色的十六進制值。

枚舉中定義方法

Swift Code

enum Color {
    case red, green, blue

    func description() -> String {
        switch self {
        case .red:
            return "Color is red."
        case .green:
            return "Color is green."
        case .blue:
            return "Color is blue."
        }
    }
}

let greenColor = Color.green

print(greenColor.description())
// Output: Color is green.

在以上代碼中,我們在 Color 枚舉中添加了一個 description 方法,用于返回顏色的描述信息。

本文我們介紹了在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關聯值等相關的內容。通過與 TypeScript 語法的對比,希望能幫助您更好地理解 Swift 的相關特性。


責任編輯:武曉燕 來源: 全棧修仙之路
相關推薦

2021-04-13 05:36:18

C#null 可控

2019-11-12 08:53:32

PG數據數據庫

2021-10-12 09:20:02

數據庫SQL腳本

2021-02-27 17:13:21

前端代碼邏輯

2020-11-17 08:07:29

存儲類型瀏覽器

2023-12-06 14:23:24

2023-04-27 08:15:09

2025-03-25 10:49:13

2020-01-09 09:56:47

Java集合框架

2020-02-23 23:29:07

Python編程開發

2024-03-01 13:48:00

Git配置系統

2019-07-12 08:45:07

開源微服務框架

2018-04-26 09:03:48

ApacheWeb服務器

2019-08-29 09:15:30

負載均衡算法備份

2024-02-26 00:00:00

前端工具Space.js

2023-08-01 11:14:07

開源Api軟件

2021-11-04 11:54:30

Linux內存系統

2016-09-19 14:42:12

大數據SQLPig

2018-11-07 15:44:29

虛擬化服務器桌面

2023-10-31 08:23:54

網絡命令Linux
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产午夜精品一区二区三区嫩草 | 一区二区三区国产在线观看 | 亚洲成人一区二区三区 | 蜜桃精品视频在线 | 国产精品二区三区在线观看 | 看a网站| 国产精品久久久久久久久久久免费看 | 国产精品美女www爽爽爽 | 国产精品视屏 | 亚洲a视| 成人伊人网 | 一区不卡在线观看 | 国产福利观看 | 欧美 日韩 国产 一区 | 亚洲精品一级 | 久久尤物免费一区二区三区 | 妞干网视频 | 国产精品国产成人国产三级 | 国产成人99久久亚洲综合精品 | 亚洲欧美在线视频 | 中文字幕加勒比 | 第一av| 成人无遮挡毛片免费看 | 欧美综合一区二区三区 | 美国一级毛片a | 在线观看亚 | 日韩精品视频在线 | 99热国产在线播放 | 天堂中文字幕av | 黄网站涩免费蜜桃网站 | 91精品国产综合久久久久久 | 亚洲精品在线看 | 精品国产黄a∨片高清在线 成人区精品一区二区婷婷 日本一区二区视频 | 九九久久精品 | 99热视 | 在线免费中文字幕 | 天啪 | 欧美另类视频在线 | 欧美精品三区 | 欧美一区二区三区在线观看 | 国产日韩欧美一区 |