本文我們將介紹在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關(guān)聯(lián)值等相關(guān)的內(nèi)容。如果你尚未安裝 Xcode 和配置 Swift 開發(fā)環(huán)境,請您先閱讀這篇文章。
接下來,我們啟動 Xcode,然后選擇 "File" > "New" > "Playground"。創(chuàng)建一個新的 Playground 并命名為 "Enumerations"。
在 Swift 中,枚舉(Enum)是一種特殊的數(shù)據(jù)類型,它允許你定義一組相關(guān)的值。這些值是你在程序中會用到的一些具體選項。
在 Swift 中,我們使用 enum 關(guān)鍵字定義一個枚舉,在枚舉體內(nèi)使用 case 關(guān)鍵字定義不同的情況,每個情況表示枚舉的一個成員。
Swift Code
enum Color { case red case green case blue}let greenColor = Color.greenprint(greenColor)// Output: green
在以上代碼中,我們定義了一個名為 Color 的枚舉,包含了三種顏色。
TypeScript Code
enum Color { Red, Green, Blue}let color: Color = Color.Green;console.log(color);// Output: 1
有了 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 協(xié)議來使枚舉遵循可迭代的協(xié)議,從而實現(xiàn)對枚舉成員的遍歷。
Swift Code
enum Color: CaseIterable { case red, green, blue}for color in Color.allCases { print(color)}/**Output: redgreenblue*/
在上面的代碼中,我們讓 Color 枚舉遵循 CaseIterable 協(xié)議,以便枚舉該枚舉的所有成員。
TypeScript Code
enum Color { Red, Green, Blue}for(let colorKey in Color) { console.log(colorKey)}/**Output: "0" "1" "2" "Red" "Green" "Blue" */
Swift 中的枚舉可以關(guān)聯(lián)原始值,這些原始值可以是整數(shù)、浮點數(shù)、字符串等類型。枚舉的原始值為每個成員提供了一個默認值,方便我們在不同的上下文中使用。
Swift Code
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,后續(xù)成員的原始值遞增。
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 中,數(shù)值枚舉的原始值也是遞增的,與 Swift 中的數(shù)值枚舉相似。
Swift Code
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,為每個成員顯式賦予了一個字符串原始值。
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 中的枚舉不僅可以有原始值,還可以攜帶關(guān)聯(lián)值。關(guān)聯(lián)值允許在定義枚舉的時候指定每個成員攜帶的數(shù)據(jù)類型。這樣,每個枚舉成員都可以攜帶不同類型的數(shù)據(jù)。
Swift Code
import Foundation// 定義 Shape 枚舉描述不同的圖形enum Shape { case circle(radius: Double) case square(side: Double) case rectangle(width: Double, height: Double)}// 使用關(guān)聯(lián)值創(chuàng)建不同的圖形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 枚舉,其中的每個成員都可以攜帶不同類型的關(guān)聯(lián)值,表示不同的圖形。有了 Shape 枚舉之后,我們可以創(chuàng)建一個 calculateArea 函數(shù),來計算不同圖形的面積。
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.27433388230814let areaOfSquare = calculateArea(shape: square) // 16let areaOfRectangle = calculateArea(shape: rectangle) // 12
在以上代碼中,我們定義了一個函數(shù) calculateArea,根據(jù)圖形的類型計算圖形的面積。通過關(guān)聯(lián)值,我們可以輕松地提取不同圖形的屬性進行計算。在 TypeScript 中,由于并沒有直接對應(yīng) Swift 枚舉關(guān)聯(lián)值的語法,我們可以使用 TypeScript 的聯(lián)合類型來模擬這種行為。
TypeScript Code
interface Circle { kind: 'circle'; radius: number;}interface Square { kind: 'square'; side: number;}interface Rectangle { kind: 'rectangle'; width: number; height: number;}// 使用聯(lián)合類型表示不同的圖形type Shape = Circle | Square | Rectangle;
在以上代碼中,我們使用接口和聯(lián)合類型來定義不同圖形的數(shù)據(jù)結(jié)構(gòu)。之后,我們也可以定義一個 calculateArea 函數(shù)來計算不同圖形的面積。
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.274333882308138const areaOfSquare = calculateArea(square); // 16const 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.greenprint(greenColor.hexValue)// Output: #00FF00
在以上代碼中,我們?yōu)?nbsp;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.greenprint(greenColor.description())// Output: Color is green.
在以上代碼中,我們在 Color 枚舉中添加了一個 description 方法,用于返回顏色的描述信息。
本文我們介紹了在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關(guān)聯(lián)值等相關(guān)的內(nèi)容。通過與 TypeScript 語法的對比,希望能幫助您更好地理解 Swift 的相關(guān)特性。
本文鏈接:http://www.tebozhan.com/showinfo-26-64510-0.htmlSwift 枚舉類型,你知道幾個?
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 使用 Spring Boot 創(chuàng)建自己的 ChatGPT 應(yīng)用程序
下一篇: 透明度怎么轉(zhuǎn)換為16進制值