Reputation: 15
As you can see from. the title, i am trying to turn the content of a text field into a variable. I have used this code:
@IBOutlet weak var TextField: UITextField!
let variable = TextField.text
UPDATE: I created a new project with new code, which I have inserted above. The only errors I got was this: Cannot use instance member 'TextField' within property initializer; property initializers run before 'self' is available.
Upvotes: 1
Views: 3647
Reputation: 6547
UPDATE: I think you are having different issues than the one you mentioned, after your answer has changed a few times, I understood that you want to use the value of a UITextField to use it for your WebView URL to load and also to check the prefix sometimes in a different state later on. But you are actually loading the webview on viewDidLoad which won't work for you as you didn't have yet the chance to change your UITextField value manually from your phone/simulator.
That means there can be different work-case scenarios and flows, that you might want to think and implement which one best works for your business needs. For now, if you want the value of a UITextField to be stored in a variable and access the latest value or the first value of it, you can follow my original answer:
If you want variable
to be a stored property, here you store the value of textfield.text
in the exact moment you instantiate variable
, then the issue in your code is that textfield.text
can be nil
, so you would have better handled that as:
let variable = textfield.text ?? ""
If you want variable
to be a computed property, in this case everytime you try to access variable
and get its value it will calculate it based on the code in its closure, so it will fetch the latest textfield.text
value everytime you try to get variable
value:
var variable: String? { // optional, remember textfield.text can return nil
return textfield.text
}
If you always want to return something you could instead declare it this way, and return an empty string in case textfield.text is nil (remember, textfield.text
can be nil
):
var variable: String { // not optional, you give a "" default value if nil
return textfield.text ?? ""
}
Upvotes: 1