【问题标题】:String length in Swift 1.2 and Swift 2.0 [duplicate]Swift 1.2 和 Swift 2.0 中的字符串长度 [重复]
【发布时间】:2015-06-16 23:33:42
【问题描述】:

在以前版本的 Swift 中,我有以下代码。

func myfunc(mystr: String) {
    if mystr.utf16Count >= 3 {

使用最新版本的 Swift 1.2,我现在收到以下错误。

'utf16Count' is unavailable: Take the count of a UTF-16 view instead, i.e. count(str.utf16)

所以我将代码更改如下:

func myfunc(mystr: String) {
    if count(mystr.utf16) >= 3 {

但这不起作用。我现在收到以下错误消息。

'(String.UTF16View) -> _' is not identical to 'Int16'

使用 Swift 1.2 获取字符串长度的正确方法是什么?

【问题讨论】:

  • 右键点击计数,然后“跳转到定义”。
  • 从 Swift 4+ 你可以使用,str.count

标签: swift string


【解决方案1】:

您可以使用以下扩展名:

extension String {
     var length: Int { return count(self)         }  // Swift 1.2
}

你可以使用它:

if mystr.length >= 3 {

}

或者你可以直接这样算:

if count(mystr) >= 3{

}

这也对我有用:

if count(mystr.utf16) >= 3 {

}

对于 Swift 2.0:

extension String {
    var length: Int {
        return characters.count
    }
}
let str = "Hello, World"
str.length  //12

另一个扩展:

extension String {
    var length: Int {
        return (self as NSString).length
    }
}
let str = "Hello, World"
str.length //12

如果你想直接使用:

let str: String = "Hello, World"
print(str.characters.count) // 12

let str1: String = "Hello, World"
print(str1.endIndex) // 12

let str2 = "Hello, World"
NSString(string: str2).length  //12

【讨论】:

  • 是的,我不明白 OP 的错误,它也对我有用。
  • 感谢您的建议。即使使用 count(mystr) 我也看到错误 '(String) -> _' 与 'Int16' 不同。
  • 啊,我找到了。基于 NSManagedObject 的类有一个名为“count”的字段,该字段定义为覆盖全局计数函数的 Int16。感谢您的完整性检查。
【解决方案2】:

您必须使用包含属性计数的字符属性:

yourString.characters.count

【讨论】:

    【解决方案3】:

    Swift 2.0 更新

    extension String {
        var count: Int { return self.characters.count }
    }
    

    用途:

    var str = "I love Swift 2.0!"
    var n = str.count
    

    Helpful Progamming Tips and Hacks

    【讨论】:

      【解决方案4】:

      这里是一体的——复制自here

      let str = "Hello"
      let count = str.length    // returns 5 (Int)
      
      extension String {
          var length: Int { return countElements(self) }  // Swift 1.1
      }
      extension String {
          var length: Int { return count(self)         }  // Swift 1.2
      }
      extension String {
          var length: Int { return characters.count    }  // Swift 2.0
      }
      

      【讨论】:

        【解决方案5】:

        count(mystr)是正确的方式,不需要转换编码。

        这个:if count(mystr.utf16) >= 3 没问题,只要你这样做Int16(3)

        编辑:这是一个旧答案。 OP 更新了他的问题以反映 Swift 2 并且上述答案是正确的。

        【讨论】:

        • 感谢您的建议,但这给了我错误 '(String) -> _' is not same to 'Int16'。
        • 不是在 Swift 2 中推荐的方法,而是参见上面的@Dharmesh Kheni 的答案。
        • @King-Wizard 我知道,半年前就看过了。
        猜你喜欢
        • 2015-10-21
        • 1970-01-01
        • 2015-12-03
        • 2016-09-11
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 2015-08-26
        相关资源
        最近更新 更多