Jaebi의 Binary는 호남선

Swift - 문법 (Object and Classes, Enumerations and Structures, Concurrency) 본문

Swift

Swift - 문법 (Object and Classes, Enumerations and Structures, Concurrency)

jaebijae 2024. 6. 12. 04:56

목차

    Objects and Classes

    • class → `class`
    var shape = Shape()
    shape.numberOfSides = 7
    var shapeDescription = shape.simpleDescription()
    • use `init` to create initializer
      • `self` is used to distinguish the name property from the name argument to the initializer
    class NamedShape {
        var numberOfSides: Int = 0
        var name: String
        init(name: String) {
           self.name = name
        }
    }
    • use `deinit` to deinitialize: perform cleanup before object is deallocated
    • subclass → `subclassName: superClassName`
    • override superclass’s implementation with `override`
    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)."
    }
    • properties can have a getter and a setter
      • you can provide explicit name in parentheses after `set`
    class EquilateralTriangle: NamedShape {
        var sideLength: Double = 0.0
        var perimeter: Double {
            get {
                 return 3.0 * sideLength
            }
            set {
                sideLength = newValue / 3.0
            }
        }
    }
    • if value before `?` is `nil`, everything after the `?` is ignored and whole is `nil`
      • `let sideLength = optionalSquare?.sideLength` → `nil` if `optionalSqaure` is `nil`

    Enumerations and Structures

    • enumeration → `enum`
    • enum can have methods with them
    enum Rank: Int {
        case ace = 1
        case two, three, four, five, six, seven, eight, nine, ten
        case jack, queen, king
        func simpleDescription() -> String {
            switch self {
            case .ace:
                return "ace"
            case .jack:
                return "jack"
            case .queen:
                return "queen"
            case .king:
                return "king"
            default:
                return String(self.rawValue)
            }
        }
    }
    • enum can have values associated with the case → values determined when instance is made
    enum ServerResponse {
        case result(String, String)
        case failure(String)
    }
    let success = ServerResponse.result("6:00 am", "8:09 pm")
    let failure = ServerResponse.failure("Out of cheese.")
    switch success {
    case let .result(sunrise, sunset):
        print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
    case let .failure(message):
        print("Failure...  \(message)")
    }
    • structure → `struct`
    struct Card {
        var rank: Rank
        var suit: Suit
        func simpleDescription() -> String {
            return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
        }
    }
    • structures are always copied when passed around in code, but classes are passed by reference

    Concurrency

    • asynchronous function → `async`, `await`
    func fetchUsername(from server: String) async -> String {
        let userID = await fetchUserID(from: server)
        if userID == 501 {
            return "John Appleseed"
        }
        return "Guest"
    }
    • use `async let` to call asynchronous function run in parallel, and `await` to use the value it returns
    func connectUser(to server: String) async {
        async let userID = fetchUserID(from: server)
        async let username = fetchUsername(from: server)
        let greeting = await "Hello \(username), user ID \(userID)"
        print(greeting)
    }
    • use `Task` to call asynchronous functions from synchronous code, without waiting
    Task {
        await connectUser(to: "primary")
    }
    // Prints "Hello Guest, user ID 97"