9

I am currently trying to change a few NSArrays into NSMutableArrays however as I am new to Swift and Xcode I don't really understand the errors and how to fix them.

This is the code I have:

var names: NSMutableArray = []
var dates: NSMutableArray = []
var values: NSMutableArray = []
var images: NSMutableArray = []

override func viewWillAppear(animated: Bool) {
    self.tableView.reloadData()

    if enterButtonTapped == false {
        addTransactionButton.enabled = false
    } else {
        addTransactionButton.enabled = true
    }

    var tempNames: NSArray = NSUserDefaults.standardUserDefaults().arrayForKey("names")!
    var tempDates: NSArray = NSUserDefaults.standardUserDefaults().arrayForKey("dates")!
    var tempValues: NSArray = NSUserDefaults.standardUserDefaults().arrayForKey("values")!
    var tempImages: NSArray = NSUserDefaults.standardUserDefaults().arrayForKey("images")!

    names = tempNames.mutableCopy() as NSMutableArray
    dates = tempDates.mutableCopy() as NSMutableArray
    values = tempValues.mutableCopy() as NSMutableArray
    images = tempImages.mutableCopy() as NSMutableArray

    println(names)
    println(dates)
    println(values)
    println(images)
}

I currently receive the error: fatal error: unexpectedly found nil while unwrapping an Optional value

Also, I know that I shouldn't really be using NSUserDefaults for this purpose, but I find it way easier than using a plist or Core Data etc... Since it's my first app I just want to keep things simple.

2 Answers 2

28

You are better off using this syntax to set the variables

if let tempNames: NSArray = NSUserDefaults.standardUserDefaults().arrayForKey("names") {
   names = tempNames.mutableCopy() as NSMutableArray
}
Sign up to request clarification or add additional context in comments.

Comments

20

Also just to convert NSArray to NSMutableArray in Swift:

 let name: NSArray = ["John","Jake","Tom"]

 var myNewName = NSMutableArray(array:name)

1 Comment

this is cleaner than using mutableCopy()

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.