日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

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

來源: 責編: 時間:2024-01-18 17:40:51 210觀看
導讀本文我們將介紹在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關聯值等相關的內容。如果你尚未安裝 Xcode 和配置 Swift 開發環境,請您先閱讀這篇文章。接下來,我們啟動 Xcode,然后選擇 "File" > "New" > "Playgr

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

接下來,我們啟動 Xcode,然后選擇 "File" > "New" > "Playground"。創建一個新的 Playground 并命名為 "Enumerations"。voB28資訊網——每日最新資訊28at.com

在 Swift 中,枚舉(Enum)是一種特殊的數據類型,它允許你定義一組相關的值。這些值是你在程序中會用到的一些具體選項。voB28資訊網——每日最新資訊28at.com

定義一個枚舉

在 Swift 中,我們使用 enum 關鍵字定義一個枚舉,在枚舉體內使用 case 關鍵字定義不同的情況,每個情況表示枚舉的一個成員。voB28資訊網——每日最新資訊28at.com

Swift CodevoB28資訊網——每日最新資訊28at.com

enum Color {    case red    case green    case blue}let greenColor = Color.greenprint(greenColor)// Output: green

在以上代碼中,我們定義了一個名為 Color 的枚舉,包含了三種顏色。voB28資訊網——每日最新資訊28at.com

TypeScript CodevoB28資訊網——每日最新資訊28at.com

enum Color {    Red,    Green,    Blue}let color: Color = Color.Green;console.log(color);// Output: 1

使用 switch 處理枚舉

有了 Color 枚舉后,我們可以使用 switch 語句來處理枚舉。voB28資訊網——每日最新資訊28at.com

Swift CodevoB28資訊網——每日最新資訊28at.com

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 CodevoB28資訊網——每日最新資訊28at.com

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 協議來使枚舉遵循可迭代的協議,從而實現對枚舉成員的遍歷。voB28資訊網——每日最新資訊28at.com

Swift CodevoB28資訊網——每日最新資訊28at.com

enum Color: CaseIterable {    case red, green, blue}for color in Color.allCases {    print(color)}/**Output: redgreenblue*/

在上面的代碼中,我們讓 Color 枚舉遵循 CaseIterable 協議,以便枚舉該枚舉的所有成員。voB28資訊網——每日最新資訊28at.com

TypeScript CodevoB28資訊網——每日最新資訊28at.com

enum Color {    Red,    Green,    Blue}for(let colorKey in Color) {    console.log(colorKey)}/**Output: "0" "1" "2" "Red" "Green" "Blue" */

枚舉原始值

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

數值原始值

Swift CodevoB28資訊網——每日最新資訊28at.com

enum Weekday: Int {    case sunday = 1    case monday    case tuesday    case wednesday    case thursday    case friday    case saturday}let today: Weekday = .tuesdaylet rawValue: Int = today.rawValueprint(rawValue)// Output: 3

在以上代碼中,我們定義了一個表示星期的枚舉 Weekday,并為每個成員顯式賦予了一個原始值。默認情況下,第一個成員的原始值為 1,后續成員的原始值遞增。voB28資訊網——每日最新資訊28at.com

TypeScript CodevoB28資訊網——每日最新資訊28at.com

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 中的數值枚舉相似。voB28資訊網——每日最新資訊28at.com

字符串原始值

Swift CodevoB28資訊網——每日最新資訊28at.com

enum Direction: String {    case up = "UP"    case down = "DOWN"    case left = "LEFT"    case right = "RIGHT"}let move: Direction = .uplet directionString: String = move.rawValueprint(directionString)// Output: UP

在以上代碼中,我們定義了一個字符串枚舉 Direction,為每個成員顯式賦予了一個字符串原始值。voB28資訊網——每日最新資訊28at.com

TypeScript CodevoB28資訊網——每日最新資訊28at.com

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 中也是類似的,允許為每個成員指定字符串類型的原始值。voB28資訊網——每日最新資訊28at.com

枚舉關聯值

Swift 中的枚舉不僅可以有原始值,還可以攜帶關聯值。關聯值允許在定義枚舉的時候指定每個成員攜帶的數據類型。這樣,每個枚舉成員都可以攜帶不同類型的數據。voB28資訊網——每日最新資訊28at.com

Swift CodevoB28資訊網——每日最新資訊28at.com

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 函數,來計算不同圖形的面積。voB28資訊網——每日最新資訊28at.com

Swift CodevoB28資訊網——每日最新資訊28at.com

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.27433388230814let areaOfSquare = calculateArea(shape: square) // 16let areaOfRectangle = calculateArea(shape: rectangle) // 12

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

TypeScript CodevoB28資訊網——每日最新資訊28at.com

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 函數來計算不同圖形的面積。voB28資訊網——每日最新資訊28at.com

TypeScript CodevoB28資訊網——每日最新資訊28at.com

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.274333882308138const areaOfSquare = calculateArea(square); // 16const areaOfRectangle = calculateArea(rectangle); // 12

枚舉中定義計算屬性

Swift CodevoB28資訊網——每日最新資訊28at.com

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.greenprint(greenColor.hexValue)// Output: #00FF00

在以上代碼中,我們為 Color 枚舉增加了一個計算屬性 hexValue,用于表示顏色的十六進制值。voB28資訊網——每日最新資訊28at.com

枚舉中定義方法

Swift CodevoB28資訊網——每日最新資訊28at.com

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.greenprint(greenColor.description())// Output: Color is green.

在以上代碼中,我們在 Color 枚舉中添加了一個 description 方法,用于返回顏色的描述信息。voB28資訊網——每日最新資訊28at.com

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


voB28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-64510-0.htmlSwift 枚舉類型,你知道幾個?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 使用 Spring Boot 創建自己的 ChatGPT 應用程序

下一篇: 透明度怎么轉換為16進制值

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 达拉特旗| 新宾| 儋州市| 邢台县| 卫辉市| 赫章县| 资溪县| 宁德市| 沁源县| 台江县| 尉氏县| 武强县| 荣昌县| 龙胜| 重庆市| 星座| 宁阳县| 安顺市| 介休市| 托里县| 行唐县| 金门县| 邹城市| 新泰市| 阜新市| 凤阳县| 寻乌县| 新龙县| 临高县| 土默特右旗| 吕梁市| 和林格尔县| 永定县| 乐东| 新蔡县| 清涧县| 吉首市| 阿拉善右旗| 乐昌市| 云龙县| 金寨县|