Simplest way to throw an error/exception with a custom message in Swift 2?

前端 未结 10 1869
走了就别回头了
走了就别回头了 2020-12-22 15:57

I want to do something in Swift 2 that I\'m used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java):



        
10条回答
  •  佛祖请我去吃肉
    2020-12-22 16:39

    Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError that implements the LocalizedError protocol.

    struct DisplayableError: Error, LocalizedError {
        let errorDescription: String?
    
        init(_ description: String) {
            errorDescription = description
        }
    }
    

    Usage for throwing:

    throw DisplayableError("Out of pixie dust.")
    

    Usage for display:

    let messageToDisplay = error.localizedDescription
    

提交回复
热议问题