27

I have a variable on my class:

var list = []

and I use it on a function of my class:

func chargeData (data: NSArray){
    list = data
}

It worked well on my project in Swift 2.3 but when I have updated it to XCode8 and Swift3 it gives to me the following error:

Empty collection literal requires an explicit type

so I have added a typecast to my list variable:

var list = [] as! NSArray

but it gives to me the following alert:

Forced cast of 'NSArray' to same type has no effect

I know that an alert does not broke the application but I would like to solve this error in a proper way.

Did someone got the same error and solved it properly?

Thanks in advance!

3
  • 2
    You would have to do var list:NSArray = []. It's ok if you just replace it with another one. But it is not mutable itself, so var list:NSMutableArray = [] would be better I suppose.
    – Eric Aya
    Commented Sep 14, 2016 at 11:43
  • @EricAya What do you really mean with the fact that is not mutable itself? I know that mutable means that it can change its values but I am not really sure what do you mean with "mutable itself". Commented Sep 14, 2016 at 11:53
  • CodeDifferent explains it in their answer. var/let and NSArray/NSMutableArray.
    – Eric Aya
    Commented Sep 14, 2016 at 12:24

4 Answers 4

30

This error occurs since implicit conversions are abolished so you have to tell the compiler the explicit type (of the ArrayLiteral []):

var list: NSArray = []
// or
var list = [] as NSArray
13

The Swift 5 guided tour is pretty explicit about creating empty arrays or dictionaries: https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html#ID461 towards the end of the first section.

To create an empty array or dictionary, use the initializer syntax.

let emptyArray = [String]()
let emptyDictionary = [String: Float]()
7

Update swift 4 :

var array = [] as [String]
2

You are mixing ObjectiveC (NSArray) and Swift (Array<T>). Items inside an NSArray are assumed to be NSObject and its subclasses, while Swift has no clue what T is since the array is empty and hence type inference doesn't work.

If you declare it like this:

var data: NSArray = []

there will be a conflict since var means mutable in Swift, but NSArray is immutable in ObjC. You can get around that by changing it to NSMutableArray, which is a subclass of NSArray:

let data = NSMutableArray() // note that we don't need var here
                            // as NSMutableArray is already mutable

If you want to keep data as Swift's Array, give it a type:

var data = [MyDataModel]()
// or
var data = [AnyObject]()

// usage:
chargeData(data: data as NSArray)
1
  • Perfect! Object: var urls = [String](); Caller: sm.urls.append("word!"); print(sm.urls[0]); Commented Jul 3, 2018 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.