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의 ν™œμš©

  • λ‹€μ–‘ν•œ λ©”μ„œλ“œκ°€ μ‘΄μž¬ν•œλ‹€.

    • get() 은 κ²°κ³Όλ₯Ό throwingν•˜λŠ” ν•¨μˆ˜μ²˜λŸΌ λ³€ν™˜κ°€λŠ₯ν•œ ν•¨μˆ˜μ΄λ‹€. (Success valueλ₯Ό λ¦¬ν„΄ν•œλ‹€)

Result νƒ€μž…μ„ μ‚¬μš©ν•˜λŠ” μ΄μœ λŠ”?

  • 성곡, μ‹€νŒ¨μ˜ 경우λ₯Ό κΉ”λ”ν•˜κ²Œ μ²˜λ¦¬ν•  수 μžˆλ‹€.

  • κΈ°μ‘΄ μ—λŸ¬μ²˜λ¦¬λ₯Ό μ™„μ „νžˆ λŒ€μ²΄ν•˜λ €λŠ” λͺ©μ μ΄ μ•„λ‹ˆλΌ, μ—λŸ¬ μ²˜λ¦¬μ— λ‹€μ–‘ν•œ μ˜΅μ…˜μ„ μ œκ³΅ν•˜λŠ”κ²ƒμ΄λ‹€.

  • μ—λŸ¬νƒ€μž…μ„ λͺ…μ‹œμ μœΌλ‘œ μ„ μ–Έν•΄μ„œ νƒ€μž… μΊμŠ€νŒ…μ΄ λΆˆν•„μš”ν•΄μ§„λ‹€.

Networkμ—μ„œ Result νƒ€μž…μ˜ ν™œμš©

Last updated