Reputation: 11
Using Swift5. UI (not storyboard), being new to Xcode, after retrieving Text Field STRING from user, 1) how do I CONVERT the string to an integer so that I can perform math calculations from user responses to multiple text fields?.. and 2) where does the code go?
Upvotes: 0
Views: 446
Reputation: 11
Sorry, (I'm really new at this) for not including my code earlier. Hope this helps.
import SwiftUI
struct ContentView: View {
@State var xUSERNAME: String = ""
@State var xUSERNAME2: String = ""
@State var xMATH: Int = 2
var body: some View {
VStack(alignment: .leading) {
Text("Hello World!")
TextField("Enter User Name...", text: $xUSERNAME)
.foregroundColor(.black)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("YOUR USER NAME: \(xUSERNAME)")
.fontWeight(.bold)
TextField("Enter User Name...", text: $xUSERNAME2)
.foregroundColor(.black)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("YOUR USER NAME: \(xUSERNAME2)")
.fontWeight(.bold)
Text("YOUR USER NAME: \(xUSERNAME)\(xUSERNAME2)")
Text("\(xUSERNAME)")
}.padding()
}
}
Upvotes: 1
Reputation: 3396
1)
@State private var textfieldInput = ""
var Int1: Int {
return Int(textfieldInput) ?? 0 // String to Int conversion is always return optional.
}
//some code
TextField("Text", text: $textfieldInput)
2) How shall wie tell, if we don't know your code? But I tried my best above to show the concept.
Upvotes: 1
Reputation: 954
In the following app, resultString
is the computed property that convert string to Int. This expression is an Optional since String can be anything when we try.
import SwiftUI
struct ContentView: View {
@State private var num: Int = 0
@State private var text: String = "0"
private var resultInt: Int {
return self.num*self.num
}
private var resultString: String {
if let num = Int(self.text) { // Here it convert the string to an integer
return String(num*num)
}
return "0"
}
var body: some View {
VStack {
TextField("String Number",text: self.$text)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Int Number", value: self.$num, formatter: NumberFormatter())
.textFieldStyle(RoundedBorderTextFieldStyle())
Spacer()
Text("Square is \(self.resultInt)").font(.title)
Text("Square is \(self.resultString)").font(.title)
Spacer()
}.padding()
}
}
@rick-h comment down if you need clarification
Upvotes: 1