Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

에러 핸들링 예제 #87

Closed
Youngminah opened this issue Nov 9, 2021 · 0 comments
Closed

에러 핸들링 예제 #87

Youngminah opened this issue Nov 9, 2021 · 0 comments
Labels

Comments

@Youngminah
Copy link
Owner

Youngminah commented Nov 9, 2021

enum ValidationError: Int, Error {
    case emptyString = 401
    case invalidInt = 402
    case invalidDate = 403
}


func validateUserError(text: String) throws -> Bool {
    
    guard !(text.isEmpty) else {
        throw ValidationError.emptyString
    }
    
    guard Int(text) != nil else {
        print("숫자가 아닙니다.")
        throw ValidationError.invalidInt
    }
    
    //사용자가 입력한 값이 날짜 형태로 변환이 되는 숫자인지 아닌지
    guard chectDateFormat(text: text) else {
        print("날짜 형태가 아닙니다.")
        throw ValidationError.invalidDate
    }
    return true
}

do {
    let result = try validateUserInput(text: "20211101")
} catch ValidationError.emptyString {
    print("값이 비어 있습니다.")
} catch ValidationError.invalidInt {
    print("숫자 값이 아닙니다.")
} catch ValidationError.invalidDate {
    print("날짜 값이 아닙니다.")
}

//또는
do {
    let result = try validateUserInput(text: "20211101")
} catch {
    switch error {
    case ValidationError.invalidDate: print("날짜 값이 아닙니다." ValidationError.invalidDate.rawValue)
    case ValidationError.emptyString: print("값이 비어 있습니다.")
    case ValidationError.invalidInt: print("숫자 값이 아닙니다.")
    }
}

do-try catch

  • 사용자가 선택할 수 있는 옵션이 아닌경우 사용

if - else 문

  • 사용자가 선택지가 있는 경우 사용
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant