Search code examples
iosswiftswift-extensions

Cannot convert return expression of type 'UIColor' to return type '[UIColor]' on UIColor extension


I'm writing a simple extension for UIColor to take a hex string based off 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))
    }
}

Now I can clearly see that the return type is UIColor, but when I try to use it:

UIColor.colorWithString("F9264E")

I get:

Cannot convert return expression of type 'UIColor' to return type '[UIColor]'

What's going on?


Solution

  • You need to post an entire statement that uses your extension. My guess is that you are doing an assignment and the variable you are assigning to is of type array of UIColor:

    var colors: [UIColor]
    
    colors = UIColor.colorWithString("F9264E")
    

    That would give you the exact error you are reporting.

    Instead you'd need code like this:

    colors = [UIColor.colorWithString("F9264E")]
    

    or

    var colors = [UIColor]()
    colors.append(UIColor.colorWithString("F9264E"))