Why I can not create a function with return & ldquo; Array & rdquo; rather NSArray to Swift?

advertisements

Swift 2.0 - Xcode 7.2

I would like to create one function like this:

func returnExampleArray() -> Array {

    return ["term1","term2"]

}

With the return of the function as "Array" default in Swift 2.0, but the Xcode 7.2 only allow return with NSArray, like this:

func returnExampleArray() -> NSArray {

    return ["term1","term2"]
}

Why I don't can use Array instead NSArray?


Fogmeister's answer is correct but it doesn't really tell you why.

The Array type is a generic type. You can't simply return an Array because Swift needs to know what you can put in that array. Your first function should be written:

func returnExampleArray() -> Array<String>
{
    return ["term1","term2"]
}

But, of course there is special notation for arrays. Where you would put Array<T> where T is some type, you can put [T] instead, which is syntactic sugar for the original version, and that is where Fogmeister's answer comes from.

NSArray is an Objective-C type and is not generic (but you can almost think of it as being like Array<AnyObject>) That's why your second example works. However, a lot of stuff goes on behind the scenes in that the array ["term1","term2"] has to be converted into an NSArray of NSStrings before it is returned.