Can I throw from class init() in Swift with constant string loaded from file?

[Update] Swift Version >= 2.2

Since Swift 2.2 you can break the execution of a class initialiser without the need of populating all stored properties

class FileStruct {
    let text: String

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

Swift Version <= 2.1

Currently in Swift class you cannot break the execution of an initialiser before every stored property has been initialized.

On the other hand, you don’t have this constraint with structs so

struct FileStruct {
    var text: String

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

You can also avoid the do/catch block

struct FileStruct {
    var text: String

    init() throws {
        text = try String(contentsOfFile: "/Users/me/file.txt", encoding: NSUTF8StringEncoding)
    }
}

Finally I replaced NSString with String since we are using Swift, not Objective-C 😉

Leave a Comment

techhipbettruvabetnorabahisbahis forumu