Search code examples
swiftsyntaxnsdatansurlthrows

What is the meaning of keyword "throws" in Swift?


What is meaning of "throws" keyword here:

This code take so long to be executed and i think "throws" keyword in the image above related:

let url = URL(string:"\(APIs.postsImages)\(postImg)")
let imgData = try? Data.init(contentsOf: url)
self.postImage.image = UIImage.init(data: imgData)

Solution

  • init() throws can return more information about the failure and let the caller decide if they care about it or not. Read a useful post about it here.

    To indicate that a function, method, or initializer can throw an error, you need to write the throws keyword in the function’s declaration after its parameters. A function marked with throws is called a throwing function. If the function specifies a return type, you write the throws keyword before the return arrow.

    func thisFunctionCanThrowErrors() throws -> String
    

    or in real code it might look like this:

    enum PossibleErrors: Error {
        case wrongUsername
        case wrongPassword
    }
    
    func loggingIn(name: String, pass: String) throws -> String {
    
        if name.isEmpty { 
            throw PossibleErrors.wrongUsername 
        }
        if pass.isEmpty { 
            throw PossibleErrors.wrongPassword 
        }
        return "Fine"
    }
    

    The throwing functions like this must be called using one of the following try operators:

    • try
    • try?
    • try!

    Using init() throws you can break the execution of a class initialiser without the need of populating all stored properties:

    class TestClass {
    
        let textFile: String
    
        init() throws {
            do {
                textFile = try String(contentsOfFile: "/Users/swift/text.txt", 
                                            encoding: NSUTF8StringEncoding)
            catch let error as NSError {
                throw error
            }
        }
    }
    

    And in a structure you can even avoid the do/catch block:

    struct TestStruct {
    
        var textFile: String
    
        init() throws {
            textFile = try String(contentsOfFile: "/Users/swift/text.txt", 
                                        encoding: NSUTF8StringEncoding)
        }
    }