Reputation: 507
I am in xCode 7.3 playground and learning Swift 2.0.
I have an array as follows:
var arrayName:Array = [1, 2, 3, 4, "Mike"]
And i'm getting the following error:
type of expression is ambiguous without more context
Now when i remove the string from the array the error disappears, however apparently Swift allows multiple types in arrays so I dont understand why its erroring?
any ideas?
cheers
Upvotes: 3
Views: 7233
Reputation: 2161
Another option, which is useful when concatenating 2 arrays of objects that conform to the same protocol, is to upcast each array individually to the protocol:
let arrayName = [1, 2, 3, 4] as [AnyObject] + ["Mike"] as [AnyObject]
As said, this will come in more handy when working with protocols:
protocol Foo {}
struct Bar: Foo {}
struct Baz: Foo {}
let barArray = [Bar()]
let bazArray = [Baz()]
let fooArray = barArray as [Foo] + bazArray as [Foo]
Upvotes: 1
Reputation: 2994
Check this out
Ray Wenderlich on Swift Arrays
So, arrays can only contain one type of object? What if I want varied types? In Swift you are highly encouraged to make strongly typed arrays that contain only one type of object, with syntax like this:
var goodArray: [String] = ["foo", "bar"]
That said, technically you can still create arrays that contain multiple types of objects. However, before you do this you should be asking yourself why you want to do this. In most cases it does not make the best sense and you can likely engineer your solution to be cleaner. With that said, here’s how you can create a Swift array with varying types of objects within it by using AnyObject:
var brokenArray: [AnyObject] = ["foo", 1, 12.23, true]
TL;DR:- Arrays are strongly typed on iOS. If you need to insert elements of multiple type, make them of type "AnyObject". Would not recommend this though.
Upvotes: 3
Reputation: 6114
Error says all. You can fix it like this, for example:
var arrayName: Array<AnyObject> = [1, 2, 3, 4, "Mike"]
or, simplier,
var arrayName = [1, 2, 3, 4, "Mike"]
then arrayName
will get type Array<NSObject>
implicitly.
Its all about type recognizing. You have two options: use explicit full type declaration, or you can let swift compiler try recognize type
Upvotes: 3