从String到NSString的条件强制转换始终成功

时间:2019-08-09 22:05:09

标签: swift nsstring

我正在尝试消除此警告。我在此行下收到警告:

let removeHashTag = (currentText as? NSString)?.substring(from: 1)

我已经知道它是字符串格式,但是当我尝试键入它时,不会给我提供子字符串选项。

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)
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

虽然您从1开始使用常量值作为子字符串,但是您可以轻松地使用

let removedHashTag = currentText.dropFirst()
let editedString = String(removedHashTag)

答案 1 :(得分:0)

删除所有问号。

(currentText as NSString).substring(from: 1)

更好的是,根本不要转换为NSString。 Swift String具有相同的功能:

currentText.suffix(currentText.count-1)