edoriggio edoriggio - 2 months ago 8
iOS Question

Changing the text of a UITextView from one view to another

I have a problem with my code. When I type in a UITextField in another view controller the value is saved in a variable (var oraDa: String!). I would like to change the text of a UITextView if the text typed is nil or is not nil. Here's the code:

var oraDa: String!
var oDF: String!

override func viewDidLoad() {
super.viewDidLoad()

oDF = "From "

if oraDa == nil {

oDF = nil

}

finalText.text = "\(oDF!)" + "\(oraDa!)"

}


I want that when


oraDa != nil


oDF is equal to "From"

but if oraDa is nil, oDF is equal to nil

Answer

In: finalText.text = "\(oDF!)" + "\(oraDa!)" you are force unwrapping these string optionals. If they are nil then your code will crash.

If you are taking `oraDa' in from another view, then you should do your logic as follows:

override func viewDidLoad() {
   super.viewDidLoad()

   if oraDa == nil || oraDa == "" {

       oDF = nil
       finalText.text = "";
   } else {
       oDF = "From "
       finalText.text = "\(oDF!)" + "\(oraDa!)"
   }
}