Effective difference between short and long array initialization form

The latest experiment in the Swift Guided Tour asks the reader:

Change the function anyCommonElements (_: _ :) to make a function that returns an array of elements that have any two sequences in common.

My first quick jump on modification:

func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> [T.Generator.Element] { var commonElements = [T.Generator.Element]() for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { commonElements.append(lhsItem) } } } return commonElements } 

I get an error related to my initializing the commonElements array in line 2 in Xcode 7.1.1:

Incorrect use of '[]' to call a value of non-functional type '[T.Generator.Element.Type]'

However, if I just change the initialization to use the longhand form to create an empty array in line 2, everything works fine and without errors:

 func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> [T.Generator.Element] { var commonElements = Array<T.Generator.Element>() // Longhanded empty array for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { commonElements.append(lhsItem) } } } return commonElements } 

The Swift documentation says:

The Swift array type is written completely as Array<Element> , where Element is the type of values ​​that the array can be stored. You can also write the type of the array in abbreviated form as [Element] . Although the two forms are functionally identical, an abbreviated form is preferred and is used in this guide when it comes to array type.

(Emphasis added.)

If they are “functionally identical”, why do I get the error in the first example above, apparently only because I used the short form to create an empty array? Or maybe more likely - I lack a fundamental understanding of the problem?

+7
arrays swift
source share

No one has answered this question yet.

See similar questions:

twenty
Why can't I create an empty array of a nested class?

or similar:

1915
How to declare and initialize an array in Java?
924
How to initialize all elements of an array with the same value?
773
What is the difference between "Array ()" and "[]" when declaring a JavaScript array?
633
How to get the difference between two arrays in JavaScript?
618
All possible array initialization syntaxes
431
How to use arrays in C ++?
105
Using protocols in the form of array types and functional parameters in fast
one
Fast expansion of an array with equivalent elements cannot cause an index (from :)
one
Array Swift Syntax Type Mismatch
0
How do you use fully defined types in arrays defined using the short form?

All Articles