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