Jaebi의 Binary는 호남선

Swift - 문법 (Protocols and Extensions, Error Handling, Generics) 본문

Swift

Swift - 문법 (Protocols and Extensions, Error Handling, Generics)

jaebijae 2024. 6. 12. 05:18

목차

    Protocols and Extensions

    • protocol (interface) → `protocol`
    protocol ExampleProtocol {
         var simpleDescription: String { get }
         mutating func adjust()
    }

     

    • classes, enumerations, and structures can all adopt protocols
      • modify structure → `mutating`
    class SimpleClass: ExampleProtocol {
         var simpleDescription: String = "A very simple class."
         var anotherProperty: Int = 69105
         func adjust() {
              simpleDescription += "  Now 100% adjusted."
         }
    }
    struct SimpleStructure: ExampleProtocol {
         var simpleDescription: String = "A simple structure"
         mutating func adjust() {
              simpleDescription += " (adjusted)"
         }
    }
    • add functionality to an existing type → `extension`
    extension Int: ExampleProtocol {
        var simpleDescription: String {
            return "The number \(self)"
        }
        mutating func adjust() {
            self += 42
        }
    }
    print(7.simpleDescription)

     

    Error Handling

    • represent errors → `Error` protocol
    enum PrinterError: Error {
        case outOfPaper
        case noToner
        case onFire
    }
    • throw an error → `throw`, mark a function that can throw an error → `throws`
    func send(job: Int, toPrinter printerName: String) throws -> String {
        if printerName == "Never Has Toner" {
            throw PrinterError.noToner
        }
        return "Job sent"
    }
    • Error handling #1 → `do-catch`
      • mark code that can throw an error → `try`
    do {
        let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
        print(printerResponse)
    } catch PrinterError.onFire {
        print("I'll just put this over here, with the rest of the fire.")
    } catch let printerError as PrinterError {
        print("Printer error: \(printerError).")
    } catch {
        print(error)
    }
    • Error handling #2 → `try?`
      • convert result to an optional, if throws an error result is nil
      • `let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")`

     

    Generics

    • name inside angle brackets to make generic function or type → `<Int>`
    • specify list of requirements → `where`
    • Writing `<T: Equatable>` is the same as writing `<T> ... where T: Equatable`

     

    Reference

     

    Documentation

     

    docs.swift.org