본문 바로가기
Swift

[TIL] A Swift Tour 대충이지만 읽기 완료!

by yj.yoon 2023. 9. 13.

내 글은 구독자를 위해 쓰여 있지 않다. 약간 서브 브레인 역할을 블로그가 하고 있기 때문에. 친절한 포스트는 아니다.ㅎㅎ

이렇게 쓰다가 나도 찾지 못하거나, 이해 못하진 않을까 하는 생각도 든다. 

 

이전 글 : https://hensorflow.tistory.com/46

 

[TIL] 정말로 처음 시작하는 Swift

오늘도,,, 일은 안하고 동료 분들이랑 스몰(이 아닌 것 같은)토크와 개인 공부를 하고 있다. (담배 피우는 사람들 따라나가기도 함ㅋㅋㅋ) 크로스 플랫폼 앱 개발을 한다해도 네이티브가 필요한

hensorflow.tistory.com

 

이어서 읽어가기!

 


async - await

예제 코드

func fetchUserID(from server: String) async -> Int {
    if server == "Primary" {
    return 97
    }
    return 501
}

func fetchUsername(from server: String) async -> String {
    let userID = await fetchUserID(from: server)
    if userID == 501 {
       return "John Appleseed"
    }
    return "Guest"
}

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)
}

Task {
    await connectUser(to: "Primary")
}
// Prints "Hello Guest, user ID 97"

 

- Task 를 사용해서 return을 기다리지 않고 동기 코드에서 비동기 함수를 호출한다. (Use Task to call asynchronous functions from synchronous code, without waiting for them to return.)

 

 

Protocols and Extensions

프로토콜 선언

protocol ExampleProtocol {

     var simpleDescription: String { get }

     mutating func adjust()

}

 

protocol의 간단한 정의는 requirements that suit a particular task or piece of functionality. = 특정 작업이나 기능을 구현하기 위한 요구 사항. 자바의 인터페이스와 비슷하다고 한다. 명시적이고 독립적인 타입과 같다. 정의할 때 기본적으로 var로 프로퍼티를 정의한다.

 

** mutating : struct, enum의 프로퍼티(속성, 변수)를 수정해야 하는 경우 해당 메소드의 동작을 변경하도록 하는 것

 

// 클래스 - 참조 타입

class SimpleClass: ExampleProtocol {

     var simpleDescription: String = "A very simple class."

     var anotherProperty: Int = 69105 // 속성

     func adjust() { // 메소드

          simpleDescription += "  Now 100% adjusted."

     }

}

var a = SimpleClass()

a.adjust()

let aDescription = a.simpleDescription

결과 : A very simple class.  Now 100% adjusted.

 

// 구조체 - 값 타입, 상속 불가

struct SimpleStructure: ExampleProtocol {

     var simpleDescription: String = "A simple structure"

     mutating func adjust() {

          simpleDescription += " (adjusted)"

     }

}

var b = SimpleStructure()

b.adjust()

let bDescription = b.simpleDescription

결과 : A simple structure (adjusted)

 

 

익스텐션

extension Int: ExampleProtocol {

    var simpleDescription: String {

        return "The number \(self)"

    }

    mutating func adjust() {

         self += 42

        }

}

 

print(7.simpleDescription) // The number 7

 

var num: Int = 7

print(num.simpleDescription); // 7

num.adjust();

print(num.simpleDescription); // 49

 

 

에러 핸들링

 

enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "job sent"
}

do {
    let printerResponse = try send(job: 1040, 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)
}

 

 

동료 분이 다음 프로젝트에서는 에러 추적이 쉽도록 코드를 작성해보자 하셨다. 공감!

내일도 공부할 시간이 있다면, 튜토리얼 프로젝트를 진행해보려고 한다.

개념 끝