[英]Conditional cast from String to NSString always succeeds
I'm trying to eliminate this warning.我正在尝试消除此警告。 I get the warning under this line:
我在这一行下收到警告:
let removeHashTag = (currentText as? NSString)?.substring(from: 1)
I know it already in a string format, and but when I tried typing it won't give me the option to substring.我知道它已经是字符串格式,但是当我尝试输入时,它不会给我子字符串的选项。
func searchGetTextAutoComplete(_ text: String?) {
var currentText: String
if text == nil {
ViewAnimation.move(tableView, withAlpha: 0.0)
print("textfield is nil")
} else {
if (text?.count ?? 0) == 0 {
ViewAnimation.move(tableView, withAlpha: 0.0)
print("textfield has zero length")
} else {
currentText = text ?? ""
// # included in the beggining of the string
//MARK: you dont needs to downcasted if it already a string
if (text?.count ?? 0) > 1 {
let removeHashTag = (currentText as? NSString)?.substring(from: 1)
SketchManager.shared()?.searchTagsOrUsername(removeHashTag, withCompletion: { success, message, searchResultDic in
if success {
self.followersArray = (searchResultDic?["follower"] as? [String])!
let resultArray = searchResultDic?["result"] as? [Any]
// NSLog(@"%@", resultArray);
if resultArray?.count == 0 {
self.noResultsPlacehoder.isHidden = false
ViewAnimation.move(self.tableView, withAlpha: 0.0)
} else {
self.itemsArray.removeAll()
for dic in resultArray as? [[String : Any]] ?? [] {
self.itemsArray.append(dic)
}
self.tableView.reloadData()
ViewAnimation.move(self.tableView, withAlpha: 1.0)
self.noResultsPlacehoder.isHidden = true
}
}
})
} else {
noResultsPlacehoder.isHidden = false
ViewAnimation.move(tableView, withAlpha: 0.0)
}
}
}
}
While you are using constant value for substring from 1 you can easily use当您为 1 的子字符串使用常量值时,您可以轻松使用
let removedHashTag = currentText.dropFirst()
let editedString = String(removedHashTag)
Remove all the question marks.去掉所有的问号。
(currentText as NSString).substring(from: 1)
Even better, don't cast to NSString at all.更好的是,根本不要转换为 NSString。 Swift String gives you the same powers:
Swift String 给你同样的权力:
currentText.suffix(currentText.count-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.