Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NSArray to NSMutableArray in Swift

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.

like image 434
user3746428 Avatar asked Aug 27 '14 22:08

user3746428


2 Answers

You are better off using this syntax to set the variables

if let tempNames: NSArray = NSUserDefaults.standardUserDefaults().arrayForKey("names") {
   names = tempNames.mutableCopy() as NSMutableArray
}
like image 192
Anthony Kong Avatar answered Sep 24 '22 00:09

Anthony Kong


Also just to convert NSArray to NSMutableArray in Swift:

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

 var myNewName = NSMutableArray(array:name)
like image 32
CodeOverRide Avatar answered Sep 21 '22 00:09

CodeOverRide