import SwiftUI
struct DataTypesDemoView: View {
@State private var intValue: Int = 10
@State private var doubleValue: Double = 3.14
@State private var stringValue: String = "Hello"
@State private var boolValue: Bool = true
var body: some View {
VStack(spacing: 20) {
Text("Int value: \(intValue)")
Text("Double value: \(doubleValue)")
Text("String value: \(stringValue)")
Text("Bool value: \(boolValue ? "True" : "False")")
Button("Refresh Values") {
intValue = Int.random(in: 1...100)
doubleValue = Double.random(in: 0...10).rounded(toPlaces: 2)
stringValue = ["Hello", "Swift", "World", "Data"].randomElement() ?? "Swift"
boolValue.toggle()
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
.padding()
}
}
extension Double {
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
struct DataTypesDemoView_Previews: PreviewProvider {
static var previews: some View {
DataTypesDemoView()
}
}This app uses @State variables to hold values of four basic Swift data types: Int, Double, String, and Bool. Each value is shown in a Text view with a label.
The "Refresh Values" button changes these values to new random or sample data. For example, the Int changes to a random number between 1 and 100, the Double changes to a random decimal rounded to 2 places, the String picks a random word from an array, and the Bool toggles between true and false.
This shows how to declare and use basic data types in SwiftUI and update the UI reactively when values change.