Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing different types of value in Array in Swift

Tags:

swift

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]
like image 668
Boon Avatar asked Jun 16 '14 04:06

Boon


People also ask

Can array have different data types in Swift?

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].

Can an array store many different types of values?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

How do you store different values 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.

Is array value type in Swift?

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.


1 Answers

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'
like image 111
Bryan Chen Avatar answered Oct 06 '22 20:10

Bryan Chen