0
0
Swiftprogramming~5 mins

Array creation and type inference in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is type inference in Swift when creating an array?
Type inference means Swift automatically figures out the type of the array based on the values you put inside it, so you don't have to write the type explicitly.
Click to reveal answer
beginner
How do you create an empty array of integers in Swift?
You can create it by writing: var numbers: [Int] = [] or var numbers = [Int]().
Click to reveal answer
beginner
What happens if you write <code>let fruits = ["Apple", "Banana", "Cherry"]</code> in Swift?
Swift infers that fruits is an array of strings: [String].
Click to reveal answer
intermediate
Can Swift infer the type of an array if it contains mixed types like [1, "two", 3]?
No, Swift requires all elements in an array to be of the same type. Mixed types cause a compile error.
Click to reveal answer
beginner
How do you create an array with repeated values in Swift?
Use Array(repeating: value, count: number). For example, Array(repeating: 0, count: 3) creates [0, 0, 0].
Click to reveal answer
What type does Swift infer for let numbers = [1, 2, 3]?
A[Int]
B[Double]
C[String]
D[Any]
Which of these is a valid way to create an empty array of strings in Swift?
Avar names = [String]
Bvar names = []
Cvar names = [1, 2, 3]
Dvar names: [String] = []
What happens if you try to create let mixed = [1, "two", 3] in Swift?
ASwift infers [Any]
BSwift infers [String]
CCompile error due to mixed types
DSwift infers [Int]
How do you create an array with five zeros in Swift?
A[0, 0, 0, 0, 0]
BArray(repeating: 0, count: 5)
CArray(0, 5)
Drepeat(0, 5)
If you write var items = ["pen", "pencil"], what is the type of items?
A[String]
B[Character]
C[Any]
D[Int]
Explain how Swift uses type inference when you create an array with values.
Think about how Swift guesses the type based on what you put inside the array.
You got /3 concepts.
    Describe two ways to create an empty array in Swift and why you might need to specify the type.
    Remember empty arrays have no values, so Swift can't guess the type automatically.
    You got /3 concepts.