【问题标题】:Conditional cast from String to NSString always succeeds从 String 到 NSString 的条件转换总是成功
【发布时间】:2019-12-17 15:24:25
【问题描述】:

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

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

【问题讨论】:

  • 你为什么要强制转换为NSStringString 有获取子字符串的方法。
  • 那是我的想法,但它不会给我那个选项

标签: swift nsstring


【解决方案1】:

当您使用从 1 开始的子字符串的常量值时,您可以轻松地使用

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

【讨论】:

  • 我这样做了,但它给了我一个错误,即无法将类型“String.SubSequence”(又名“子字符串”)的值转换为预期的参数类型“字符串?”
【解决方案2】:

删除所有问号。

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

更好的是,根本不要强制转换为 NSString。 Swift String 给你同样的力量:

currentText.suffix(currentText.count-1)

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多