Q:

Replace space with underscore in Swift 4 Text Fields

I have a Text Field in my User Registration screen called; Username. 
To avoid users leaving this field empty - and to make it easy for them to use a username that simply combines their First and Last names - I currently have an IBAction that triggers when "Editing did End" to take the value from the Full Name in lowercase. 
@IBAction func fullNameEditingEnded(_ sender: Any) {
    let userName = fullnameTextfield.text?.lowercased()
    usernameTextfield.text = userName
    }

I would like to replace the space with an underscore. What is the best approach to do this? Is it a for in loop or is there something simpler?

A:

Try this Also it's better to trim end spaces as not to be replace-able with _
let aString = "first last"
let newString = aString.replacingOccurrences(of: " ", with: "_")

@IBAction func fullNameEditingEnded(_ sender: Any) {
    let userName = fullnameTextfield.text?.lowercased()
    usernameTextfield.text = userName.replacingOccurrences(of: " ", with: "_")
}

