在 Swift 4 个文本字段中将 space 替换为下划线

Replace space with underscore in Swift 4 Text Fields

我的用户注册屏幕中有一个文本字段调用; 用户名

为了避免用户将此字段留空 - 并让他们更容易使用简单地结合他们的名字和姓氏的用户名 - 我目前有一个 IBAction 触发当“Editing did End”从小写全名中获取值时。

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

我想用下划线替换 space。最好的方法是什么?是for in循环还是有更简单的东西?

试试这个另外,最好 trim 结束空格,以免被 _

替换
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: "_")
}