我正在为UIColor编写一个简单的扩展名,以取消基于this answer的十六进制字符串:
import UIKit
extension UIColor {
public static func colorWithString (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))
}
}
现在我可以清楚地看到返回类型是UIColor
,但是当我尝试使用它时:
UIColor.colorWithString("F9264E")
我明白了:
无法转换类型' UIColor'的返回表达式返回类型' [UIColor]'
发生了什么?
答案 0 :(得分:4)
您需要发布使用您的扩展程序的整个语句。我的猜测是你正在做一个赋值,你指定的变量是UIColor类型的数组:
var colors: [UIColor]
colors = UIColor.colorWithString("F9264E")
这会给你报告的确切错误。
相反,你需要这样的代码:
colors = [UIColor.colorWithString("F9264E")]
或
var colors = [UIColor]()
colors.append(UIColor.colorWithString("F9264E"))