I'd like my class init() in Swift to throw an error if something goes wrong with loading a file into a string within the class. Once the file is loaded, the string will not be altered, so I would prefer to use let. This works:
class FileClass {
var text: NSString = ""
init() throws {
do {
text = try NSString( contentsOfFile: "/Users/me/file.txt", encoding: NSUTF8StringEncoding ) }
catch let error as NSError {
text = ""
throw error
}
}
}
but when I replace
var text: NSString = ""
with
let text: NSString
I get an All stored properties of a class instance must be initialized before throwing from an initializer error.
I've tried various approaches such as to make text optional
let text: NSString?
but haven't found any that work. It it possible to have text be loaded from a file, immutable, and for init() to throw an error? Can I have my cake and eat it three?
Many thanks in advance!