I want to make button, which pressed will show us random textfield (from 3 textfields: username, username2 or username3).
Currently I have something like this, but don’t know how to make it possible.
struct Test: View {
/// @State private var names : ??? - I don't know what should be there
@State private var username: String = ""
@State var username2: String = ""
@State var username3: String = ""
var body: some View {
NavigationView {
VStack {
TextField("Your name", text: $username)
TextField("Your name2", text: $username2)
TextField("Your name3", text: $username3)
Button(action: randomName) {
Text("draw")
}
}
Text("names.text") /// it doesn't work
.foregroundColor(.black)
.font(.largeTitle)
}
}
}
private func randomName() {
let names = ["(username)", "(username2)", "(username3)"]
}
}
I have tried to add everything into first @State private var names, but nothing work properly. Maybe I am just trying in wrong way? Or it shouldn’t be done by ‘let names’?
I don’t know and have no idea.
2
Answers
first of all you just need to add randomName as State.
The
username
,username2
andusername3
properties are already strings. No need to use string interpolation when you create your array.Swift arrays have a handy
randomElement()
method. The only wrinkle is that it returns an optional – It will returnnil
if the array is empty, so you need to handle this. There are three ways:if let
to skip the code if the result isnil
??
) to provide a default value if the result isnil
!
. This is generally not a good approach, although it could work in this case because the array cannot be empty.Option 1:
Option 2:
Option 3: