Result

Result type

๐Ÿ’ก ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ๊ฒฝ์šฐ, ์—๋Ÿฌ๋ฅผ ์™ธ๋ถ€๋กœ ๋˜์ง€์ง€ ์•Š๊ณ , Result ํƒ€์ž…์— ํ•จ์ˆ˜ ์‹คํ–‰ ๊ฒฐ๊ณผ๋ฅผ ๋‹ด์•„ ๋ฆฌํ„ดํ•  ์ˆ˜ ์žˆ๋‹ค.

  • ๋‚ด๋ถ€์ ์œผ๋กœ ์—ด๊ฑฐํ˜•์œผ๋กœ ๊ตฌํ˜„๋˜์–ด์žˆ๋‹ค.

    • enum **Result<Success, Failure>** where Failure: Error

    • ์„ฑ๊ณต๊ณผ ์‹คํŒจ ์ •๋ณด๋ฅผ ํ•จ๊ป˜ ๋‹ด์•„์„œ ๋ฆฌํ„ดํ•œ๋‹ค.

    • Failure์˜ ๊ฒฝ์šฐ, Error ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•ด์•ผํ•œ๋‹ค.

throwing๊ณผ์˜ ๋น„๊ต

// 1๋‹จ๊ณ„: ์—๋Ÿฌํƒ€์ž… ์ •์˜

enum HeightError: Error {
    case maxHeight
    case minHeight
}

// 2๋‹จ๊ณ„: throwing ํ•จ์ˆ˜ ์ •์˜
func checkingHeight(height: Int) -> throws Bool {
    if height > 190 {
        throw HeightError.maxHeight
    else if height < 130 {
        throw HeightError.minHeight
    } else {
        if height >= 160 {
            return true
        } else {
            return false
        }
    }
}

// 3๋‹จ๊ณ„: ์—๋Ÿฌ์ฒ˜๋ฆฌ
do {
    let _ = try checkingHeight(height: 200)
    print("๊ฐ€๋Šฅ")
} catch {
    print("๋ถˆ๊ฐ€๋Šฅ"
}

// 2๋‹จ๊ณ„: Result type ํ•จ์ˆ˜ ์ •์˜
func CheckingHeight(height: Int) -> Result<Bool, HeightError> {
    if height > 190 {
        return Result.failure(HeightError.maxHeight)
    } else if height < 130 {
        return Result.failure(HeightError.minHeight)
    } else {
        if height >= 160 {
            return Result.success(true)
        } else {
            return Result.success(false)
        }
    }
}

// 3๋‹จ๊ณ„: ์—๋Ÿฌ์ฒ˜๋ฆฌ
let result = CheckingHeight(height: 200)

switch result {
case .success(let data):
    print("๊ฐ€๋Šฅ")
case .failure(let error):
    print("๋ถˆ๊ฐ€๋Šฅ")
}

Result Type์˜ ํ™œ์šฉ

do {
    let data = try result.get()
    print("๊ฒฐ๊ณผ = \(data)")
} catch {
    print(error)
}
  • ๋‹ค์–‘ํ•œ ๋ฉ”์„œ๋“œ๊ฐ€ ์กด์žฌํ•œ๋‹ค.

    • get() ์€ ๊ฒฐ๊ณผ๋ฅผ throwingํ•˜๋Š” ํ•จ์ˆ˜์ฒ˜๋Ÿผ ๋ณ€ํ™˜๊ฐ€๋Šฅํ•œ ํ•จ์ˆ˜์ด๋‹ค. (Success value๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค)

Result ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ๋Š”?

  • ์„ฑ๊ณต, ์‹คํŒจ์˜ ๊ฒฝ์šฐ๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

  • ๊ธฐ์กด ์—๋Ÿฌ์ฒ˜๋ฆฌ๋ฅผ ์™„์ „ํžˆ ๋Œ€์ฒดํ•˜๋ ค๋Š” ๋ชฉ์ ์ด ์•„๋‹ˆ๋ผ, ์—๋Ÿฌ ์ฒ˜๋ฆฌ์— ๋‹ค์–‘ํ•œ ์˜ต์…˜์„ ์ œ๊ณตํ•˜๋Š”๊ฒƒ์ด๋‹ค.

  • ์—๋Ÿฌํƒ€์ž…์„ ๋ช…์‹œ์ ์œผ๋กœ ์„ ์–ธํ•ด์„œ ํƒ€์ž… ์บ์ŠคํŒ…์ด ๋ถˆํ•„์š”ํ•ด์ง„๋‹ค.

Network์—์„œ Result ํƒ€์ž…์˜ ํ™œ์šฉ

enum NetworkError: Error {
    case .someError
}

func performRequest(with url: String, completion: @escaping (Result<Data, NetworkError> -> void) {
    
    guard let url = URL(string: url) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in 
        if let error {
            completion(.failure(.someError))
            return
        }

        guard let data else {
            completion(.failure(.someError)
            return
        }

        completion(.success(data))
    }.resume()
}

performRequest(with: "address") { result in
    switch result {
    case .failure(let error):
        print(error)
    case .success(let data):
        // data ์ฒ˜๋ฆฌ
    }
}

Last updated