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 的相關特性。