Swift 枚舉類型,你知道幾個(gè)?
本文我們將介紹在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關(guān)聯(lián)值等相關(guān)的內(nèi)容。如果你尚未安裝 Xcode 和配置 Swift 開(kāi)發(fā)環(huán)境,請(qǐng)您先閱讀這篇文章。
接下來(lái),我們啟動(dòng) Xcode,然后選擇 "File" > "New" > "Playground"。創(chuàng)建一個(gè)新的 Playground 并命名為 "Enumerations"。
在 Swift 中,枚舉(Enum)是一種特殊的數(shù)據(jù)類型,它允許你定義一組相關(guān)的值。這些值是你在程序中會(huì)用到的一些具體選項(xiàng)。
定義一個(gè)枚舉
在 Swift 中,我們使用 enum 關(guān)鍵字定義一個(gè)枚舉,在枚舉體內(nèi)使用 case 關(guān)鍵字定義不同的情況,每個(gè)情況表示枚舉的一個(gè)成員。
Swift Code
enum Color {
case red
case green
case blue
}
let greenColor = Color.green
print(greenColor)
// Output: green
在以上代碼中,我們定義了一個(gè)名為 Color 的枚舉,包含了三種顏色。
TypeScript Code
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Green;
console.log(color);
// Output: 1
使用 switch 處理枚舉
有了 Color 枚舉后,我們可以使用 switch 語(yǔ)句來(lái)處理枚舉。
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é)議來(lái)使枚舉遵循可迭代的協(xié)議,從而實(shí)現(xiàn)對(duì)枚舉成員的遍歷。
Swift Code
enum Color: CaseIterable {
case red, green, blue
}
for color in Color.allCases {
print(color)
}
/**
Output:
red
green
blue
*/
在上面的代碼中,我們讓 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ù)、浮點(diǎn)數(shù)、字符串等類型。枚舉的原始值為每個(gè)成員提供了一個(gè)默認(rèn)值,方便我們?cè)诓煌纳舷挛闹惺褂谩?/p>
數(shù)值原始值
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
在以上代碼中,我們定義了一個(gè)表示星期的枚舉 Weekday,并為每個(gè)成員顯式賦予了一個(gè)原始值。默認(rèn)情況下,第一個(gè)成員的原始值為 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 = .up
let directionString: String = move.rawValue
print(directionString)
// Output: UP
在以上代碼中,我們定義了一個(gè)字符串枚舉 Direction,為每個(gè)成員顯式賦予了一個(gè)字符串原始值。
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 中也是類似的,允許為每個(gè)成員指定字符串類型的原始值。
枚舉關(guān)聯(lián)值
Swift 中的枚舉不僅可以有原始值,還可以攜帶關(guān)聯(lián)值。關(guān)聯(lián)值允許在定義枚舉的時(shí)候指定每個(gè)成員攜帶的數(shù)據(jù)類型。這樣,每個(gè)枚舉成員都可以攜帶不同類型的數(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)
在以上代碼中,我們定義了一個(gè) Shape 枚舉,其中的每個(gè)成員都可以攜帶不同類型的關(guān)聯(lián)值,表示不同的圖形。有了 Shape 枚舉之后,我們可以創(chuàng)建一個(gè) calculateArea 函數(shù),來(lái)計(jì)算不同圖形的面積。
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
}
}
// 計(jì)算不同圖形的面積
let areaOfCircle = calculateArea(shape: circle) // 28.27433388230814
let areaOfSquare = calculateArea(shape: square) // 16
let areaOfRectangle = calculateArea(shape: rectangle) // 12
在以上代碼中,我們定義了一個(gè)函數(shù) calculateArea,根據(jù)圖形的類型計(jì)算圖形的面積。通過(guò)關(guān)聯(lián)值,我們可以輕松地提取不同圖形的屬性進(jìn)行計(jì)算。在 TypeScript 中,由于并沒(méi)有直接對(duì)應(yīng) Swift 枚舉關(guān)聯(lián)值的語(yǔ)法,我們可以使用 TypeScript 的聯(lián)合類型來(lái)模擬這種行為。
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)合類型來(lái)定義不同圖形的數(shù)據(jù)結(jié)構(gòu)。之后,我們也可以定義一個(gè) calculateArea 函數(shù)來(lái)計(jì)算不同圖形的面積。
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 }
// 計(jì)算不同圖形的面積
const areaOfCircle = calculateArea(circle); // 28.274333882308138
const areaOfSquare = calculateArea(square); // 16
const areaOfRectangle = calculateArea(rectangle); // 12
枚舉中定義計(jì)算屬性
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
在以上代碼中,我們?yōu)?nbsp;Color 枚舉增加了一個(gè)計(jì)算屬性 hexValue,用于表示顏色的十六進(jìn)制值。
枚舉中定義方法
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.
在以上代碼中,我們?cè)?nbsp;Color 枚舉中添加了一個(gè) description 方法,用于返回顏色的描述信息。
本文我們介紹了在 Swift 中如何定義枚舉、遍歷枚舉、枚舉原始值、枚舉關(guān)聯(lián)值等相關(guān)的內(nèi)容。通過(guò)與 TypeScript 語(yǔ)法的對(duì)比,希望能幫助您更好地理解 Swift 的相關(guān)特性。