In Swift Programming Language, it says "An array stores multiple values of the same type in an ordered list." But I have found that you can store multiple types of values in the array. Is the description incorrect?
e.g.
var test = ["a", "b", true, "hi", 1]
Swift Array – With Elements of Different TypesIn Swift, we can define an array that can store elements of any type. These are also called Heterogenous Collections. To define an array that can store elements of any type, specify the type of array variable as [Any].
No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.
Storing Data in Arrays. Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
In Swift, Array, String, and Dictionary are all value types. They behave much like a simple int value in C, acting as a unique instance of that data.
From REPL
xcrun swift
1> import Foundation
2> var test = ["a", "b", true, "hi", 1]
test: __NSArrayI = @"5 objects" {
[0] = "a"
[1] = "b"
[2] =
[3] = "hi"
[4] = (long)1
}
3>
you can see test
is NSArray
, which is kind of AnyObject[]
or NSObject[]
What happening is that Foundation
provides the ability to convert number and boolean into NSNumber
. Compiler will perform the conversion whenever required to make code compile.
So they now have common type of NSObject
and therefore inferred as NSArray
Your code doesn't compile in REPL without import Foundation
.
var test = ["a", "b", true, "hi", 1]
<REPL>:1:12: error: cannot convert the expression's type 'Array' to type 'ArrayLiteralConvertible'
var test:Array = ["a", "b", true, "hi", 1]
<REPL>:4:18: error: cannot convert the expression's type 'Array' to type 'ExtendedGraphemeClusterLiteralConvertible'
but you can do this
var test : Any[] = ["a", "b", true, "hi", 1]
Because they have a common type, which is Any
.
Note: AnyObject[]
won't work without import Foundation
.
var test:AnyObject[] = ["a", "b", true, "hi", 1]
<REPL>:2:24: error: type 'Bool' does not conform to protocol 'AnyObject'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With