IOS9 - 无法使用类型'(String)'的参数列表调用'count'

时间:2015-09-23 13:43:37

标签: string swift count ios9

我只是迁移到Xcode7 / IOS9,我的代码的某些部分不兼容。

我从Xcode收到以下错误:

“无法使用'(String)'”

类型的参数列表调用'count'

这是我的代码:

let index   = rgba.startIndex.advancedBy(1)
  let hex     = rgba.substringFromIndex(index)
  let scanner = NSScanner(string: hex)
  var hexValue: CUnsignedLongLong = 0

  if scanner.scanHexLongLong(&hexValue)
  {
    if count(hex) == 6
    {
      red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
      green = CGFloat((hexValue & 0x00FF00) >> 8)  / 255.0
      blue  = CGFloat(hexValue & 0x0000FF) / 255.0
    }
    else if count(hex) == 8
    {
      red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
      green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
      blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
      alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
    }

1 个答案:

答案 0 :(得分:22)

在swift2中,他们对count

进行了一些更改

这是swift 1.2的代码:

let test1 = "ajklsdlka"//random string
let length = count(test1)//character counting

因为swift2代码必须是

let test1 = "ajklsdlka"//random string
let length = test1.characters.count//character counting

为了能够找到数组的长度。

此行为主要发生在swift 2.0中,因为String不再符合SequenceType协议String.CharacterView

请记住,它也改变了您在数组中迭代的方式:

var password = "Meet me in St. Louis"
for character in password.characters {
    if character == "e" {
        print("found an e!")
    } else {
    }
}

所以要非常小心,尽管很可能Xcode会给你这样的操作带来错误。

所以这就是你的代码应该如何修复你所遇到的错误(不能用'(String)'类型的参数列表调用'count'):

  let index   = rgba.startIndex.advancedBy(1)
  let hex     = rgba.substringFromIndex(index)
  let scanner = NSScanner(string: hex)
  var hexValue: CUnsignedLongLong = 0

  if scanner.scanHexLongLong(&hexValue)
  {
    if hex.characters.count == 6  //notice the change here
    {
      red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
      green = CGFloat((hexValue & 0x00FF00) >> 8)  / 255.0
      blue  = CGFloat(hexValue & 0x0000FF) / 255.0
    }
    else if hex.characters.count == 8 //and here
    {
      red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
      green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
      blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
      alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
    }