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

前端 未结 10 1877
走了就别回头了
走了就别回头了 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:36

    I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

    struct RuntimeError: LocalizedError
    {
        let message: String
    
        init(_ message: String)
        {
            self.message = message
        }
    
        public var errorDescription: String?
        {
            return message
        }
    }
    

    See this answer for more details.

提交回复
热议问题