avatarBytefer

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

9100

Abstract

convenient to use them in different contexts.</p><h2 id="82f2">Creating an Enum With Ints</h2><p id="d9d4"><b>Swift Code</b></p><div id="b75b"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Weekday</span>: <span class="hljs-title class_">Int</span> { <span class="hljs-keyword">case</span> sunday <span class="hljs-operator">=</span> <span class="hljs-number">1</span> <span class="hljs-keyword">case</span> monday <span class="hljs-keyword">case</span> tuesday <span class="hljs-keyword">case</span> wednesday <span class="hljs-keyword">case</span> thursday <span class="hljs-keyword">case</span> friday <span class="hljs-keyword">case</span> saturday }

<span class="hljs-keyword">let</span> today: <span class="hljs-type">Weekday</span> <span class="hljs-operator">=</span> .tuesday <span class="hljs-keyword">let</span> rawValue: <span class="hljs-type">Int</span> <span class="hljs-operator">=</span> today.rawValue

<span class="hljs-built_in">print</span>(rawValue) <span class="hljs-comment">// Output: 3</span></pre></div><p id="f720">In the above code, we define an enumeration <code>Weekday</code> that represents the day of the week and explicitly assigns a primitive value to each member. By default, the first member has a primitive value of 1, and subsequent members have primitive values ​​that are incremented.</p><p id="7f65"><b>TypeScript Code</b></p><div id="5830"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Weekday</span> { <span class="hljs-title class_">Sunday</span> = <span class="hljs-number">1</span>, <span class="hljs-title class_">Monday</span>, <span class="hljs-title class_">Tuesday</span>, <span class="hljs-title class_">Wednesday</span>, <span class="hljs-title class_">Thursday</span>, <span class="hljs-title class_">Friday</span>, <span class="hljs-title class_">Saturday</span> }

<span class="hljs-keyword">let</span> <span class="hljs-attr">today</span>: <span class="hljs-title class_">Weekday</span> = <span class="hljs-title class_">Weekday</span>.<span class="hljs-property">Tuesday</span>; <span class="hljs-keyword">let</span> <span class="hljs-attr">rawValue</span>: <span class="hljs-built_in">number</span> = today;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(rawValue); <span class="hljs-comment">// Output: 3</span></pre></div><p id="dac8">In TypeScript, the raw values ​​of numeric enums are also incremented, similar to numeric enums in Swift.</p><h2 id="929a">Creating an Enum With Strings</h2><p id="8cc6"><b>Swift Code</b></p><div id="a1e7"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Direction</span>: <span class="hljs-title class_">String</span> { <span class="hljs-keyword">case</span> up <span class="hljs-operator">=</span> <span class="hljs-string">"UP"</span> <span class="hljs-keyword">case</span> down <span class="hljs-operator">=</span> <span class="hljs-string">"DOWN"</span> <span class="hljs-keyword">case</span> left <span class="hljs-operator">=</span> <span class="hljs-string">"LEFT"</span> <span class="hljs-keyword">case</span> right <span class="hljs-operator">=</span> <span class="hljs-string">"RIGHT"</span> }

<span class="hljs-keyword">let</span> move: <span class="hljs-type">Direction</span> <span class="hljs-operator">=</span> .up <span class="hljs-keyword">let</span> directionString: <span class="hljs-type">String</span> <span class="hljs-operator">=</span> move.rawValue

<span class="hljs-built_in">print</span>(directionString) <span class="hljs-comment">// Output: UP</span></pre></div><p id="0bde">In the above code, we define a string enumeration <code>Direction</code>, explicitly assigning a string primitive value to each member.</p><p id="fdaa"><b>TypeScript Code</b></p><div id="2542"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Direction</span> { <span class="hljs-title class_">Up</span> = <span class="hljs-string">"UP"</span>, <span class="hljs-title class_">Down</span> = <span class="hljs-string">"DOWN"</span>, <span class="hljs-title class_">Left</span> = <span class="hljs-string">"LEFT"</span>, <span class="hljs-title class_">Right</span> = <span class="hljs-string">"RIGHT"</span> }

<span class="hljs-keyword">let</span> <span class="hljs-attr">move</span>: <span class="hljs-title class_">Direction</span> = <span class="hljs-title class_">Direction</span>.<span class="hljs-property">Up</span>; <span class="hljs-keyword">let</span> <span class="hljs-attr">directionString</span>: <span class="hljs-built_in">string</span> = move;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directionString); <span class="hljs-comment">// Output: "UP"</span></pre></div><p id="1037">String enum primitives are similar in TypeScript, allowing you to specify string type primitives for each member.</p><h1 id="da7b">Enumerations With Associated Values</h1><p id="9aa9">In Swift, enums can not only have raw values but also carry associated values. Associated values allow specifying the data type each member of the enum carries when defining it. This way, each enum member can carry data of different types.</p><p id="9138"><b>Swift Code</b></p><div id="0bfa"><pre><span class="hljs-keyword">import</span> Foundation

<span class="hljs-comment">// Define an enumeration to represent different graphic shapes</span> <span class="hljs-keyword">enum</span> <span class="hljs-title class_">Shape</span> { <span class="hljs-keyword">case</span> circle(radius: <span class="hljs-type">Double</span>) <span class="hljs-keyword">case</span> square(side: <span class="hljs-type">Double</span>) <span class="hljs-keyword">case</span> rectangle(width: <span class="hljs-type">Double</span>, height: <span class="hljs-type">Double</span>) }

<span class="hljs-comment">// Create different graphs using associated values</span> <span class="hljs-keyword">let</span> circle: <span class="hljs-type">Shape</span> <span class="hljs-operator">=</span> .circle(radius: <span class="hljs-number">3.0</span>) <span class="hljs-keyword">let</span> square: <span class="hljs-type">Shape</span> <span class="hljs-operator">=</span> .square(side: <span class="hljs-number">4.0</span>) <span class="hljs-keyword">let</span> rectangle: <span class="hljs-type">Shape</span> <span class="hljs-operator">=</span> .rectangle(width: <span class="hljs-number">3.0</span>, height: <span class="hljs-number">4.0</span>)</pre></div><p id="af9a">In the above code, we define a <code>Shape</code> enumeration, each member of which can carry different types of associated values, representing different graphic shapes. With the <code>Shape</code> enumeration, we can create a <code>calculateArea</code> function to calculate the areas of different shapes.</p><p id="7665"><b>Swift Code</b></p><div id="fa01"><pre><span class="hljs-comment">// Calculate the area of ​​a shape using associated values</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculateArea</span>(<span class="hljs-params">shape</span>: <span class="hljs-type">Shape</span>) -> <span class="hljs-type">Double</span> { <span class="hljs-keyword">switch</span> shape { <span class="hljs-keyword">case</span> .circle(<span class="hljs-keyword">let</span> radius): <span class="hljs-keyword">return</span> <span class="hljs-type">Double</span>.pi <span class="hljs-operator"></span> pow(radius, <span class="hljs-number">2</span>) <span class="hljs-keyword">case</span> .square(<span class="hljs-keyword">let</span> side): <span class="hljs-keyword">return</span> pow(side, <span class="hljs-number">2</span>) <span class="hljs-keyword">case</span> .rectangle(<span class="hljs-keyword">let</span> width, <span class="hljs-keyword">let</span> height): <span class="hljs-keyword">return</span> width <span class="hljs-operator"></span> height } }

<span class="hljs-comment">// Calculate the area of ​​different shapes</span> <span class="hljs-keyword">let</span> areaOfCircle <span class="hljs-operator">=</span> calculateArea(shape: circle) <span class="hljs-comment">// 28.27433388230814</span> <span class="hljs-keyword">let</span> areaOfSquare <span class="hljs-operator">=</span> calculateArea(shape: square) <span class="hljs-comment">// 16</span> <span class="hljs-keyword">let</span> areaOfRectangle <span class="hljs-operator">=</span> calculateArea(shape: rectangle) <span class="hljs-comment">// 12</span></pre></div><p id="f45c">In the above code, we define a function <code>calculateArea</code> to calculate the area of ​​a graphic based on its type. By associating values, we can easily extract the properties of different graphs for calculations. In TypeScript, since there is no direct syntax for Swift enum associated values, we can use TypeScript’s union types to simulate this behavior.</p><p id="ca2b"><b>TypeScript Code</b></p><

Options

div id="ffc9"><pre><span class="hljs-comment">// Define different graphics</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Circle</span> { <span class="hljs-attr">kind</span>: <span class="hljs-string">'circle'</span>; <span class="hljs-attr">radius</span>: <span class="hljs-built_in">number</span>; }

<span class="hljs-keyword">interface</span> <span class="hljs-title class_">Square</span> { <span class="hljs-attr">kind</span>: <span class="hljs-string">'square'</span>; <span class="hljs-attr">side</span>: <span class="hljs-built_in">number</span>; }

<span class="hljs-keyword">interface</span> <span class="hljs-title class_">Rectangle</span> { <span class="hljs-attr">kind</span>: <span class="hljs-string">'rectangle'</span>; <span class="hljs-attr">width</span>: <span class="hljs-built_in">number</span>; <span class="hljs-attr">height</span>: <span class="hljs-built_in">number</span>; }

<span class="hljs-comment">// Using union types to represent graphic shapes</span> <span class="hljs-keyword">type</span> <span class="hljs-title class_">Shape</span> = <span class="hljs-title class_">Circle</span> | <span class="hljs-title class_">Square</span> | <span class="hljs-title class_">Rectangle</span>;</pre></div><p id="b363">In the above code, we use interfaces and union types to define the data structures of different graphs. Afterward, we can also define a <code>calculateArea</code> function to calculate the areas of different shapes.</p><p id="df8c"><b>TypeScript Code</b></p><div id="a526"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">calculateArea</span>(<span class="hljs-params">shape: Shape</span>): <span class="hljs-built_in">number</span> { <span class="hljs-keyword">switch</span> (shape.<span class="hljs-property">kind</span>) { <span class="hljs-keyword">case</span> <span class="hljs-string">'circle'</span>: <span class="hljs-keyword">return</span> <span class="hljs-title class_">Math</span>.<span class="hljs-property">PI</span> * <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">pow</span>(shape.<span class="hljs-property">radius</span>, <span class="hljs-number">2</span>); <span class="hljs-keyword">case</span> <span class="hljs-string">'square'</span>: <span class="hljs-keyword">return</span> <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">pow</span>(shape.<span class="hljs-property">side</span>, <span class="hljs-number">2</span>); <span class="hljs-keyword">case</span> <span class="hljs-string">'rectangle'</span>: <span class="hljs-keyword">return</span> shape.<span class="hljs-property">width</span> * shape.<span class="hljs-property">height</span>; <span class="hljs-attr">default</span>: <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Invalid shape'</span>); } }

<span class="hljs-keyword">const</span> <span class="hljs-attr">circle</span>: <span class="hljs-title class_">Circle</span> = { <span class="hljs-attr">kind</span>: <span class="hljs-string">"circle"</span>, <span class="hljs-attr">radius</span>: <span class="hljs-number">3.0</span> } <span class="hljs-keyword">const</span> <span class="hljs-attr">square</span>: <span class="hljs-title class_">Square</span> = { <span class="hljs-attr">kind</span>: <span class="hljs-string">"square"</span>, <span class="hljs-attr">side</span>: <span class="hljs-number">4.0</span> } <span class="hljs-keyword">const</span> <span class="hljs-attr">rectangle</span>: <span class="hljs-title class_">Rectangle</span> = { <span class="hljs-attr">kind</span>: <span class="hljs-string">"rectangle"</span>, <span class="hljs-attr">width</span>: <span class="hljs-number">3.0</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">4.0</span> }

<span class="hljs-comment">// Calculate the area of ​​different shapes</span> <span class="hljs-keyword">const</span> areaOfCircle = <span class="hljs-title function_">calculateArea</span>(circle); <span class="hljs-comment">// 28.274333882308138</span> <span class="hljs-keyword">const</span> areaOfSquare = <span class="hljs-title function_">calculateArea</span>(square); <span class="hljs-comment">// 16</span> <span class="hljs-keyword">const</span> areaOfRectangle = <span class="hljs-title function_">calculateArea</span>(rectangle); <span class="hljs-comment">// 12</span></pre></div><h1 id="6062">Enumerations With Computed Properties</h1><p id="4bd5"><b>Swift Code</b></p><div id="a182"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Color</span> { <span class="hljs-keyword">case</span> red, green, blue

<span class="hljs-keyword">var</span> hexValue: <span class="hljs-type">String</span> {
    <span class="hljs-keyword">switch</span> <span class="hljs-keyword">self</span> {
    <span class="hljs-keyword">case</span> .red:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"#FF0000"</span>
    <span class="hljs-keyword">case</span> .green:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"#00FF00"</span>
    <span class="hljs-keyword">case</span> .blue:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"#0000FF"</span>
    }
}

}

<span class="hljs-keyword">let</span> greenColor <span class="hljs-operator">=</span> <span class="hljs-type">Color</span>.green

<span class="hljs-built_in">print</span>(greenColor.hexValue) <span class="hljs-comment">// Output: #00FF00</span></pre></div><p id="4fb7">In the above code, we added a computed property <code>hexValue</code> to the <code>Color</code>enumeration, which is used to represent the hexadecimal value of the color.</p><h1 id="b1ca">Enumerations With Methods</h1><p id="2ac9"><b>Swift Code</b></p><div id="0305"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Color</span> { <span class="hljs-keyword">case</span> red, green, blue

<span class="hljs-keyword">func</span> <span class="hljs-title function_">description</span>() -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-keyword">switch</span> <span class="hljs-keyword">self</span> {
    <span class="hljs-keyword">case</span> .red:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Color is red."</span>
    <span class="hljs-keyword">case</span> .green:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Color is green."</span>
    <span class="hljs-keyword">case</span> .blue:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Color is blue."</span>
    }
}

}

<span class="hljs-keyword">let</span> greenColor <span class="hljs-operator">=</span> <span class="hljs-type">Color</span>.green

<span class="hljs-built_in">print</span>(greenColor.description()) <span class="hljs-comment">// Output: Color is green.</span></pre></div><p id="93a9">In the above code, we added a method <code>description</code> to the <code>Color</code> enumeration to return the description information of the color.</p><p id="3023">In this article, we introduce how to define enumerations, traverse enumerations, enumerate raw values, enumerate associated values, etc. in Swift. By comparing it with TypeScript syntax, I hope it can help you better understand the related features of Swift. If you want to learn Swift, follow me on <a href="https://medium.com/@bytefer">Medium</a> or <a href="https://twitter.com/Tbytefer">Twitter</a> to read more about Swift and TS!</p><div id="1440" class="link-block"> <a href="https://medium.com/@bytefer/list/688ee7c12807"> <div> <div> <h2>Mastering TypeScript Series</h2> <div><h3>This series will introduce the core knowledge and techniques of TypeScript in the form of animations.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*624748c44fc686389a9ed7259663c489edb2ceb7.jpeg)"></div> </div> </div> </a> </div><h1 id="8575">Stackademic</h1><p id="f0d3"><i>Thank you for reading until the end. Before you go:</i></p><ul><li><i>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</i></li><li><i>Follow us on <a href="https://twitter.com/stackademichq"><b>Twitter(X)</b></a>, <a href="https://www.linkedin.com/company/stackademic"><b>LinkedIn</b></a>, and <a href="https://www.youtube.com/c/stackademic"><b>YouTube</b></a><b>.</b></i></li><li><i>Visit <a href="http://stackademic.com/"><b>Stackademic.com</b></a> to find out more about how we are democratizing free programming education around the world.</i></li></ul></article></body>

Swift Tutorials for Front-end Developers: Enumerations

Master Swift in 2024 and Start Developing Your Own iOS/macOS App

Welcome to the Mastering Swift tutorial series, in this article we will introduce defining enums, iterating through enums, enum raw values, and associated values in Swift.

Next, we launch Xcode and select “File” > “New” > “Playground”. Create a new Playground and name it “Enumerations”.

In Swift, an enumeration is a special data type that allows you to define a set of related values. These values ​​are specific options you will use in your program.

Defining an Enumeration

In Swift, we use the enum keyword to define an enumeration, and the case keyword inside the enumeration body to define different situations. Each situation represents a member of the enumeration.

Swift Code

enum Color {
    case red
    case green
    case blue
}

let greenColor = Color.green

print(greenColor)
// Output: green

In the above code, we define an enumeration called Color, which contains three colors.

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

let color: Color = Color.Green;

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

Handling Enumerations With Switch

With the Color enumeration, we can use the switch statement to process the enumeration.

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." 

Iterate Over the Members of an Enumeration

In Swift, we can use the CaseIterableprotocol to make the enumeration follow the iterable protocol to traverse the enumeration members.

Swift Code

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

for color in Color.allCases {
    print(color)
}
/**
Output: 
red
green
blue
*/

In the above code, we make the Color enumeration follow the CaseIterable protocol so that all members of the enumeration are enumerated.

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

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

Enumerations With Raw Values

In Swift, enums can be associated with raw values, which can be of types such as integers, floating-point numbers, strings, and more. The raw values for enums provide a default value for each member, making it convenient to use them in different contexts.

Creating an Enum With Ints

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

In the above code, we define an enumeration Weekday that represents the day of the week and explicitly assigns a primitive value to each member. By default, the first member has a primitive value of 1, and subsequent members have primitive values ​​that are incremented.

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

In TypeScript, the raw values ​​of numeric enums are also incremented, similar to numeric enums in Swift.

Creating an Enum With Strings

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

In the above code, we define a string enumeration Direction, explicitly assigning a string primitive value to each member.

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"

String enum primitives are similar in TypeScript, allowing you to specify string type primitives for each member.

Enumerations With Associated Values

In Swift, enums can not only have raw values but also carry associated values. Associated values allow specifying the data type each member of the enum carries when defining it. This way, each enum member can carry data of different types.

Swift Code

import Foundation

// Define an enumeration to represent different graphic shapes
enum Shape {
    case circle(radius: Double)
    case square(side: Double)
    case rectangle(width: Double, height: Double)
}

// Create different graphs using associated values
let circle: Shape = .circle(radius: 3.0)
let square: Shape = .square(side: 4.0)
let rectangle: Shape = .rectangle(width: 3.0, height: 4.0)

In the above code, we define a Shape enumeration, each member of which can carry different types of associated values, representing different graphic shapes. With the Shape enumeration, we can create a calculateArea function to calculate the areas of different shapes.

Swift Code

// Calculate the area of ​​a shape using associated values
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
    }
}

// Calculate the area of ​​different shapes
let areaOfCircle = calculateArea(shape: circle) // 28.27433388230814
let areaOfSquare = calculateArea(shape: square) // 16
let areaOfRectangle = calculateArea(shape: rectangle) // 12

In the above code, we define a function calculateArea to calculate the area of ​​a graphic based on its type. By associating values, we can easily extract the properties of different graphs for calculations. In TypeScript, since there is no direct syntax for Swift enum associated values, we can use TypeScript’s union types to simulate this behavior.

TypeScript Code

// Define different graphics
interface Circle {
    kind: 'circle';
    radius: number;
}

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

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

// Using union types to represent graphic shapes
type Shape = Circle | Square | Rectangle;

In the above code, we use interfaces and union types to define the data structures of different graphs. Afterward, we can also define a calculateArea function to calculate the areas of different shapes.

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 }

// Calculate the area of ​​different shapes
const areaOfCircle = calculateArea(circle); // 28.274333882308138
const areaOfSquare = calculateArea(square); // 16
const areaOfRectangle = calculateArea(rectangle); // 12

Enumerations With Computed Properties

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

In the above code, we added a computed property hexValue to the Colorenumeration, which is used to represent the hexadecimal value of the color.

Enumerations With Methods

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.

In the above code, we added a method description to the Color enumeration to return the description information of the color.

In this article, we introduce how to define enumerations, traverse enumerations, enumerate raw values, enumerate associated values, etc. in Swift. By comparing it with TypeScript syntax, I hope it can help you better understand the related features of Swift. If you want to learn Swift, follow me on Medium or Twitter to read more about Swift and TS!

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.
Programming
Web Development
JavaScript
iOS
Swift
Recommended from ReadMedium