Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIColor initializer - compiler error only when targeting iPhone5s

Tags:

ios

swift

The Situation:

Working from a new project: iOS > Application > Game > SpriteKit, Swift, iPhone

Here I've written a function in my GameScene.swift to accept a hex color value and alpha double. I am going by the Swift documentation, and referencing an elegant solution I saw online. I've noticed this exact code compiles, runs and displays the proper color for a build target of iPhone5 in the simulator.

But...

The exact same project wont even compile when my build target is set for iPhone5s.

the compiler error

Could not find an overload for 'init' that accepts the supplied arguments.

The function:

// colorize function takes HEX and Alpha converts then returns aUIColor object
func colorize (hex: Int, alpha: Double = 1.0) -> UIColor {
    let red = Double((hex & 0xFF0000) >> 16) / 255.0
    let green = Double((hex & 0xFF00) >> 8) / 255.0
    let blue = Double((hex & 0xFF)) / 255.0
    var color: UIColor = UIColor( red: Float(red), green: Float(green), blue: Float(blue), alpha:Float(alpha) )
    return color
}

The related call in didMoveToView:

override func didMoveToView(view: SKView) {

    // blue background color
    self.backgroundColor = colorize( 0x003342, alpha:1.0)

}

Admittedly I am very new to iOS development, but I am wondering what is going on to cause the compiler not to find this initializer?

EDIT: putting up a github momentarily

A quick gist with related files... the only one I've edited is GameScene.swift

like image 310
Joe Avatar asked Jun 13 '14 01:06

Joe


2 Answers

It probably has to do with a mismatch between Float and Double. Basically, if the arguments are expected to be CGFloats, you need to pass CGFloats.

let color = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))

What's important to understand here is that CGFloat is defined as Float on 32 bit platforms, and Double on 64 bit platforms. So, if you're explicitly using Floats, Swift won't have a problem with this on 32 Bit platforms, but will produce an error on 64 bit.

like image 174
Mick MacCallum Avatar answered Sep 20 '22 06:09

Mick MacCallum


See from the source code you should use CGFloat instead of Float

enter image description here

this should work

func colorize (hex: Int, alpha: Double = 1.0) -> UIColor {
    let red = Double((hex & 0xFF0000) >> 16) / 255.0
    let green = Double((hex & 0xFF00) >> 8) / 255.0
    let blue = Double((hex & 0xFF)) / 255.0
    var color: UIColor = UIColor( red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha:CGFloat(alpha) )
    return color
}
like image 35
Niko Adrianus Yuwono Avatar answered Sep 18 '22 06:09

Niko Adrianus Yuwono