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.
The exact same project wont even compile when my build target is set for iPhone5s.
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
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.
See from the source code you should use CGFloat instead of Float
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With