我希望名称(条目中的名称)是名为enteredName
的变量的指定值。
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
performAction()
return (true)
}
func performAction() {
if let entry = textField.text {
if entry == "my name is" + //a name {
var enteredName = //the name
print ("Your name is " + enteredName + " .")
}
}
}
我该怎么做?
答案 0 :(得分:0)
您可以执行以下操作:它将检查用户是否使用了正确的格式("我的名字是"在开头)并且不区分大小写
import Foundation
let mySentence = "My NaMe IS GioR GioR"
let mySentenceLowercased = mySentence.lowercased()
let myNameOnly = mySentence.dropFirst("my name is ".count)
if let myNameLowercased = mySentenceLowercased.components(separatedBy: "my name is ").last,
myNameOnly.lowercased() == myNameLowercased {
print("Your name is " + myNameOnly) // Your name is GioR GioR
} else {
print("Input format error. The correct format is: \"My name is [your name goes here]\"")
}
如果格式错误,例如
let mySentence = "My NaMe GioR GioR"
输出将是
//Input format error. The correct format is: "My name is [your name goes here]"
答案 1 :(得分:0)
let defaultText = "my name is"
let sentence = "My Name IS Rohit Makwana"
let lowercaseString = sentence.lowercased()
if (lowercaseString.range(of: defaultText) != nil) { // If you require default text "my name is"
let extraName = sentence.dropFirst(defaultText.count)
let name = extraName.trimmingCharacters(in: .whitespacesAndNewlines)//Remove extra space if it contains
if name.count > 0 {
print("Your name is " + name) // Your name is Rohit Makwana
}
else {
print("Input format error. The correct format is: \"My name is [your name goes here]\"")
}
}
else {
print("Input format error. The correct format is: \"My name is [your name goes here]\"")
}