我看到一些答案说在这行上使用countElements
或count
,但我在我的代码中得到错误:
if (count(cString) != 6) {
说"不能用String
类型的参数列表调用count
"
我已经尝试了一些其他的想法,但没有找到正确的解决方案,有什么想法吗?
完整功能如下:
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (count(cString) != 6) {
return UIColor.grayColor()
}
var rString = (cString as NSString).substringToIndex(2)
var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
试试cString.characters.count
。
Apple在Swift 2中更新了String
,使其不再符合count
所定义的CollectionType
协议。取而代之的是,Swift字符串现在通过characters
属性公开一个字符集合。
这是因为字符串不一定表现得像其他集合——例如,如果你向数组中添加一个数字,你期望该数组的计数增加,但是向字符串中添加某些unicode字符——例如重音,则可能不会增加字符串的长度
详情见https://developer.apple.com/swift/blog/?id=30
修改后的方法是:
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
return UIColor.grayColor()
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
注意一些vars
已经变成了let
s,因为它们从未发生过突变