-2

The array does not append with a custom class object

// Create an array with String and Double
var shoppingList = ["Eggs", 2.0]

// Append array with string object
shoppingList += ["Milk"]

// Declare an example class 
    class Foo  {
        var name : String?
        func Foo() {
            name = "Default Name"
        }
}


var foo : Foo = Foo()
shoppingList += [foo] // Error : '[NSObject]' is not identical to 'Uint8'

Why would shoppingList not append foo object?

Vebz
  • 177
  • 1
  • 1
  • 8
  • What error does the compiler give? – Cesare Feb 25 '15 at 16:57
  • Its written in the last line. // Error : '[NSObject]' is not identical to 'Uint8' – Vebz Feb 25 '15 at 17:03
  • You can't add a class `Foo` to the `shoppingList` array. – Cesare Feb 25 '15 at 17:04
  • Why is what I am trying to understand. There is no explicit type declared as I was able to add String Type and Int Type. Why would it try to compare the new appended object with Uint8? – Vebz Feb 25 '15 at 17:06
  • 1
    You got an upvote from me - just because it's a simple question doesn't make it a bad one. That compiler error doesn't help at all, and to a beginner, it's probably not readily apparent that arrays can have automatically-inferred generic type parameters. – Craig Otis Feb 25 '15 at 18:19
  • Thanks. It would have been better if everyone could share that perspective. – Vebz Feb 26 '15 at 11:32

2 Answers2

1

Swift error messages are frequently very cryptic. I'm not sure what the Uint8 is all about.

Swift arrays hold a single type. In this case, your shoppingList has been inferred to be of type [NSObject] since Swift is able to bridge "Eggs" to NSString and 2.0 to NSNumber. Both NSString and NSNumber are subclasses of NSObject, so Swift infers your array to be of type [NSObject].

If you want to put Foo() into that array, then Foo will also need to be a subclass of NSObject:

class Foo: NSObject { ...
vacawama
  • 150,663
  • 30
  • 266
  • 294
1

Alternatively to @vacawama's solution, you can explicitly specify the array element type rather than letting type inference set it for you:

var shoppingList: [AnyObject] = ["Eggs", 2.0]

The clear advantage of having the value type set to AnyObject is that you don't have to make custom classes inherit from NSObject

Antonio
  • 71,651
  • 11
  • 148
  • 165