0

Currently, testArray is an AnyObject. I'm trying to convert testArray[0][0], which is represented by testScoreOne to a string, rather than an anyObject. I don't have any anyObject declarations in my code, so I'm not sure where Xcode is getting this declaration from.

@IBAction func loadData(sender: NSArray) {
        if let testCompositeArray:NSArray = defaults.objectForKey("testScoreSATArray") as? NSArray {

            //self.showDataLabel.text = defaults.objectForKey("testScoreSATArray") as NSArray

            let testArray = defaults.objectForKey("testScoreSATArray") as NSArray

            let testScoreOne = testArray[0][0]
idmean
  • 14,540
  • 9
  • 54
  • 83
l-spark
  • 871
  • 2
  • 10
  • 25
  • 1
    You know how in my [last answer](http://stackoverflow.com/a/30381892/3925941), I mentioned how `NSArray` is an array that only holds things of type `AnyObject`, and how the problem with this is the `AnyObject` type is awkward to work with and you should consider using a typed Swift `Array` instead… – Airspeed Velocity May 21 '15 at 21:19

2 Answers2

0

It's setting the value type to AnyObject because NSArray returns the object type AnyObject.

func objectAtIndex(_ index: Int) -> AnyObject

Is there a specific reason you're choosing to use NSArray to store your values as opposed to creating a Swift array like [[String]] (2d array) or [String] (1d array). Creating your arrays using the [String] syntax, will then return the value as the type String.

socaljoker
  • 304
  • 2
  • 11
0

you have one of the following possibility how to solve:

func loadData(sender: NSArray) {
var defaults = NSUserDefaults.standardUserDefaults()
if let testCompositeArray:NSArray = defaults.objectForKey("testScoreSATArray") as? NSArray {

    //self.showDataLabel.text = defaults.objectForKey("testScoreSATArray") as NSArray


    // in case your Array contains only strings
    if let testArray = defaults.objectForKey("testScoreSATArray") as? [[String]] {
        let testScore = testArray[0][0] // this is a string
    }

    // in case your array contains different types
    if let testArray = defaults.objectForKey("testScoreSATArray") as? [AnyObject] {
        if let testScore = testArray[0][0] as? String {
            //your code for string manipulation here
        }
    }

    //in case you are sure that always will be string on this position (Swift 1.2 syntax)
    let testArray = defaults.objectForKey("testScoreSATArray") as! [AnyObject]
    let testScore = testArray[0][0] as! String

}

Kasik
  • 169
  • 1
  • 8