Double is not convertible to UInt8, Swift error - xcode

Error: Double is not convertible to UInt8 (at the last line of code)
var beweegsnelheid = NSTimeInterval()
var random3 = CGFloat(arc4random_uniform(100))
var beweegsnelheidmax = beweegsnelheid * 1.2
var beweegsnelheidmin = beweegsnelheid * 0.8
beweegsnelheid = NSTimeInterval(beweegsnelheidmin + (random3/100 * (beweegsnelheidmax - beweegsnelheidmin)))
what am I doing wrong?

You're trying to multiply a CGFloat by a Double (CGFloat is a typedef for Float).
random3/100 * (beweegsnelheidmax - beweegsnelheidmin)
Unfortunately Swift currently requires explicit type conversions all over the place.
var beweegsnelheid = NSTimeInterval()
var random3 = Float(arc4random_uniform(100))
var beweegsnelheidmax = Float(beweegsnelheid * 1.2)
var beweegsnelheidmin = Float(beweegsnelheid * 0.8)
beweegsnelheid = NSTimeInterval(beweegsnelheidmin + (random3/100 * (beweegsnelheidmax - beweegsnelheidmin)))
Just make sure you use either Float or Double throughout and you shouldn't have a problem.

Would be more obvious if it would complain that CGFloat is not convertible to Double. Swift compiler errors are sometimes really bad.
All of your values are Double, except random3. Make it a Double as well and your code should work.
let random3 = Double(arc4random_uniform(100))

Related

Minor Syntax issue regarding Swift 3.0 and a for loop

I recently just converted my code to the Swift 3.0 syntax that came with the Xcode 8 beta. I ran into several lines of code that I needed to change in order for the code to work with the latest syntax. I was able to correct all lines of code except for an error that I get regarding a for loop that I use to allow my background image to loop continuously.
The exact error message that I get is: Ambiguous reference to member '..<'
for i:CGFloat in 0 ..< 3 {
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * i), y: self.frame.midY)
background.size.height = self.frame.height
background.run(movingAndReplacingBackground)
self.addChild(background)
}
Don't use a floating point type as loop index
for i in 0 ..< 3 {
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * CGFloat(i)), y: self.frame.midY)
background.size.height = self.frame.height
background.run(movingAndReplacingBackground)
self.addChild(background)
}
Try with this:
for i in 0..<3{
let index = CGFloat(i)
//Your Code
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * index), y: self.frame.midY)
background.size.height = self.frame.height
background.run(movingAndReplacingBackground)
self.addChild(background)
}
The problem is you are performing for-loop on Int and you are also specifying it as a CGFloat. So, there a confusing between both the types.

xcode: need to convert strings to double and back to string

this is my line of code.
budgetLabel.text = String((budgetLabel.text)!.toInt()! - (budgetItemTextBox.text)!.toInt()!)
the code works, but when I try to input a floating value into the textbox the program crashes. I am assuming the strings need to be converted to a float/double data type. I keep getting errors when i try to do that.
In Swift 2 there are new failable initializers that allow you to do this in more safe way, the Double("") returns an optional in cases like passing in "abc" string the failable initializer will return nil, so then you can use optional-binding to handle it like in the following way:
let s1 = "4.55"
let s2 = "3.15"
if let n1 = Double(s1), let n2 = Double(s2) {
let newString = String( n1 - n2)
print(newString)
}
else {
print("Some string is not a double value")
}
If you're using a version of Swift < 2, then old way was:
var n1 = ("9.99" as NSString).doubleValue // invalid returns 0, not an optional. (not recommended)
// invalid returns an optional value (recommended)
var pi = NSNumberFormatter().numberFromString("3.14")?.doubleValue
Fixed: Added Proper Handling for Optionals
let budgetLabel:UILabel = UILabel()
let budgetItemTextBox:UITextField = UITextField()
budgetLabel.text = ({
var value = ""
if let budgetString = budgetLabel.text, let budgetItemString = budgetItemTextBox.text
{
if let budgetValue = Float(budgetString), let budgetItemValue = Float(budgetItemString)
{
value = String(budgetValue - budgetItemValue)
}
}
return value
})()
You need to be using if let. In swift 2.0 it would look something like this:
if let
budgetString:String = budgetLabel.text,
budgetItemString:String = budgetItemTextBox.text,
budget:Double = Double(budgetString),
budgetItem:Double = Double(budgetItemString) {
budgetLabel.text = String(budget - budgetItem)
} else {
// If a number was not found, what should it do here?
}

"Binary operator > cannot be applied to two Float operands" error

I have a conditional that looks like:
if sqrtf(powf(startTouch.x - (touches.first as! UITouch).locationInView(self.view).y, 2) + powf(startTouch.y-(touches.first as! UITouch).locationInView(self.view).y, 2)) > dragThreshold as! Float {
self.drag = false;
}
I am getting an error that says Binary operator > cannot be applied to two Float operands. I cannot understand why I can't check if a float is greater than another float. What is this error trying to tell me?
The members of a CGPoint are of type CGFloat, and assuming you are on a 64-bit architecture the native type used to store a CGFloat is Double - try treating those calculated values as Doubles (use sqrt() and pow() instead of the Float versions)... using dragThreshold as a Double as well
Using latest Xcode 7 beta 4 and SpriteKit's function override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) I did break this big chunk to smaller ones like this:
let dragThreshold: Int = 1
let startTouch = CGPointZero
let pow1 = powf(Float(startTouch.x - touches!.first!.locationInView(self.view).y), 2.0)
let pow2 = powf(Float(startTouch.y-touches!.first!.locationInView(self.view).y), 2.0)
let sq = sqrtf(pow1 + pow2)
if sq > Float(dragThreshold) {
self.drag = false;
}
This works. Basically added more conversions for powf arguments, changed 2 to 2.0
General advice - if you get some strange errors, try to break down your expression into smaller ones to isolate issue.

Using a number that is smaller then 1

Hei, I am trying my first steps in Swift coding, and I am trying to build a calculator. It should divide things though 0.5 for example, but I am getting a error message because it cant read 0.5 just full digits like 5. How can I enter number that are smaller then 1? I am very thankful for help! here is my code:
#IBAction func findBudget(sender: AnyObject) {
var enteredBudget = enterBudget.text.toInt ()
var myBudget = enteredBudget! / 0.5
resultMy.text = "My Budget: \(myBudget)"
}
You can covert your Int to a Double:
var myBudget = Double(enteredBudget!) / 0.5
You do this by getting the Double value from your string rather than an Int value. An easy way to do this is to initialize an NSString from your text and use its doubleValue property, or you could cast it to be an NSString.
let enteredBudget = NSString(string: textField.text).doubleValue
let myBudget = enteredBudget / 0.5
println(myBudget)

How to divide an entered time by a Float

So I'm making an app where you enter a time (1:32.40) and you then divide this time by a number (50). I made everything a Float so far, but that is clearly not right. How can I have the user enter the time like normal and then convert that to a Float that is easily divisible?
My Calculation function currently looks like this
func calculation() -> Bool{
raceDistance = txtRaceDistance.text
practiceDistance = txtPracticeDistance.text
goalTime = txtGoalTime.text
var fGoalTime = (goalTime as NSString).floatValue
var fRaceDistance = (raceDistance as NSString).floatValue
var fPracticeDistance = (practiceDistance as NSString).floatValue
dividedDistance = fRaceDistance / fPracticeDistance
answer = fGoalTime / dividedDistance
var answerFormat : NSString = NSString(format: "%0.2f", answer)
lblAnswer.text = String(answerFormat)
return true
}
fGoalTime is the only problem, because the user will be typing in something like (1:20.40)
I am assuming that you get an error for this line or just not the correct number.
var fGoalTime = (goalTime as NSString).floatValue
you will need to write a helper function timeStringToFloat(String) -> Float
In there you will want to use String.componentsSeparatedByString() maybe something like this:
func timeStringToFloat(timeString: String) -> Float {
let milliseconds = timeString.componentsSeparatedByString(".")[1]
let seconds = timeString.componentsSeparatedByString(.)[0].componentsSepatatedByString(":")[1]
let minutes = timeString.componentsSeparatedByString(":")[0]
//now we have them all as String
//maybe covert to float then add
let time = Float(minutes) * 60 + Float(seconds) + Float("0."+milliseconds)
return time
}

Resources