0

I have multi line texts and i save them UserDefaults. When i want to get the text sometimes return nil. But there is a text in it. How can i do that the nil does not return?

var savedReports: NSMutableArray = NSMutableArray()

    if let sR = defaults.object(forKey: "savedReports") as? NSMutableArray {
        savedReports = sR.mutableCopy() as! NSMutableArray
    }

1 Answer 1

1

The UserDefaults API will always return immutable arrays. You want:

var savedReports: NSMutableArray = NSMutableArray()

if let sR = defaults.object(forKey: "savedReports") as? NSArray {
    savedReports = sR.mutableCopy()
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why not use Swift types instead of Foundation types?
@LeoDabus uh, sorry, haven't noticed that. Then just a sad use of Foundation instead of Swift
@Xcoder123 The Swift version is independent of using Swift vs Foundation types. I don't see how that's relevant.
I could have used Swift types, and that's probably what I would do in most cases. I don't think it matters very much here, NSArray vs. [AnyObject]. Anyway, I just copied the original code sample and edited to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.