Consider the following Swift code that creates an array using type inference. What will be printed?
let numbers = [1, 2, 3, 4] print(type(of: numbers))
Look at the values inside the array and what type Swift infers from them.
Since the array contains integers, Swift infers the type as Array<Int>.
What will this Swift code print?
let mixedArray = ["apple", "banana", "cherry"] print(type(of: mixedArray))
All elements are strings, so what type does Swift infer?
All elements are strings, so Swift infers the array type as Array<String>.
What will this Swift code print?
let mixed = [1, 2.5, 3] print(type(of: mixed))
Swift will promote integers to a common type with the floating-point numbers.
Swift promotes the integers to Double to match the floating-point literal 2.5, so the array type is Array<Double>.
What error will this Swift code produce?
let invalidArray = [1, "two", 3] print(type(of: invalidArray))
Swift arrays must have elements of the same type or an explicit common type.
Swift does not allow arrays with mixed types without explicit type annotation. This code causes a compile-time error.
Given the code let empty = [], what is the inferred type of empty in Swift?
Think about how Swift needs type information to infer the type of an empty array.
Swift cannot infer the type of an empty array literal without context, so it causes a compile-time error due to ambiguous type.