Intern
How can you create a variable and assign any data type to it?
sobes.tech AI
Answer from AI
In Swift, a variable is declared using the var keyword. The data type can be explicitly specified after the variable name with a colon or inferred automatically by the compiler based on the assigned value.
// Explicit String type
var myString: String = "Hello, world!"
// Explicit Int type
var myInteger: Int = 42
// Explicit Double type
var myDouble: Double = 3.14
// Explicit Bool type
var myBoolean: Bool = true
// Type inferred automatically - String
var anotherString = "Swift"
// Type inferred automatically - Int
var anotherInteger = 100
// Type inferred automatically - Double
var anotherDouble = 2.718
For other data types, the process is similar:
// Array with explicit type
var myArray: [Int] = [1, 2, 3]
// Array with type inference
var anotherArray = ["a", "b", "c"]
// Dictionary with explicit type
var myDictionary: [String: Any] = ["key": "value", "number": 123]
// Dictionary with type inference
var anotherDictionary = ["name": "John", "age": 30]
// Custom type
struct MyStruct {
var name: String
}
var myObject: MyStruct = MyStruct(name: "Object")
// Type inference
var anotherObject = MyStruct(name: "Another Object")
Thus, a variable can be created and assigned any data type supported in Swift using the var keyword and the assignment operator =.