I'm using Xcode 7.3.1 and Swift, and i'm trying to set a random number between 1 and 50 like that: variableName = random()%50
Then i have to move an ImageView in the Y axe of that random value:
imageviewName.center.y = imageviewName.center.y - variableName
But it gives me the following error: "cannot convert value of type 'int' to expected argument type 'CGFloat'.
So I declared the variable like that:
var RandomSquirrel2 = CGFloat() but it still doesn't wok.
How can I generate a random number in Swift?
You need to covert the Int to CGFloat
imageviewName.center.y = imageviewName.center.y - CGFloat(variableName)
You need to cast variableName to CGFloat. because random() returns an Int and not A CGFloat.
imageviewName.center.y = imageviewName.center.y - CGFloat(variableName)
Related
var Rating = self.currentPerson.Rating
let c = Rating - 1
Im trying to get the value x of self.currentPerson.Rating and subtract 1 from value x. But Im only getting the error bellow.
Error : Binary operator '-' cannot be applied to operands of type
'NSNumber' and 'Int'
Question : How do I solve this?
Thanks
Problem solved.
By simply adding .intValue.
var Rating = self.currentPerson.Rating
let c = Rating.intValue - 1
Cred #luk2302
I have an array with Int values. In this array I need to get the highest value. Until here I have no problem. But now I need to convert this value to a CGFloat.
let ordersPerHour = [hour0All, hour1All, hour2All, hour3All, hour4All, hour5All, hour6All, hour7All, hour8All, hour9All, hour10All, hour11All, hour12All, hour13All, hour14All, hour15All, hour16All, hour17All, hour18All, hour19All, hour20All, hour21All, hour22All, hour23All]
let maxOrdersPerHourVal = ordersPerHour.sort().suffix(1)
How can I convert ArraySlice to CGFloat? All I have tried failed :-(
let maxOrdersPerHourVal = ordersPerHour.sort.last!
or
let maxOrdersPerHourVal = ordersPerHour.max()
will get the max value in an array.
Then you can cast as normal var floatVal = CGFloat(maxOrdersPerHourVal) if you need to cast the value.
Don't use sort here. Just use max() (or maxElement() in older versions of Swift). That will return an Int rather than a slice.
I am trying to generate a random number in Swift:
var amountOfQuestions = 2
var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
but this results in the error:
Cannot convert value of type 'Int' to expected argument type 'UInt32'
What is the problem? Any ideas on what I can do to fix this error?
Declare amountOfQuestions as a UInt32:
var amountOfQuestions: UInt32 = 2
PS: If you want to be grammatically correct it's number of questions.
First thing:
The method "arc4random_uniform" expects an argument of type UInt32, so when you put that subtraction there, it converted the '1' you wrote to UInt32.
Second thing: In swift you can't subtract a UInt32 (the '1' in your formula) from an Int (in this case 'amountOfQuestions').
To solve it all, you'll have to consider changing the declaration of 'amountOfQuestions' to:
var amountOfQuestions = UInt32(2)
That should do the trick :)
Make your amountOfQuestions variable an UInt32 rather than an Int inferred by the compiler.
var amountOfQuestions: UInt32 = 2
// ...
var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
arc4random_uniform requires a UInt32.
From the Darwin docs:
arc4random_uniform(u_int32_t upper_bound);
For example, I have the following code:
let numberOfBlocks = 3
let blockWidth = SKSpriteNode(imageNamed: "image.png").size.width
let padding = 20.0
let offsetX : Float = (self.frame.size.width - (blockWidth * numberOfBlocks + padding * (numberOfBlocks-1))) / 2
I got the error:
'Double' is not convertible to 'UInt8'
Is there a way to implicitly convert the data type (maybe only for primitive data type)?
Edit:
I know how to do the explicit conversion by using constructor of particular type as Iducool suggested. But it's not a big help to my question because we even don't know where to add the conversions. I simplified my expression in playground:
The problem is in "padding" variable, the error message is
'Double' is not convertible to 'UInt8'.
So I did the conversion:
Then the problem is in "blockWidth" variable now.
I added the conversion again:
And error message is:
Type 'UInt8' does not conform to protocol 'FloatLiteralCovertible'
The final working expression is:
Is it simple and swift? I don't think so.
There is no implicitly cast in Swift.
Easy way of conversion in swift is using constructor of particular type.
Like if you want to get Float from double then you can use Float(doubleValue) and Same way if you want to convert float to integer then you can use Int(floatValue).
In your case:
let intValue = UInt8(doubleValue)
Beware that you will lose any value after the decimal point. So, choose a better way. Above conversion is just to help you in understanding.
Note that Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.
Swift doesn't support implicitly cast anymore in Xcode6 GM. Following answer only apply to Xcode6 beta version.
I don't want to talk about implicitly cast is good or bad, but you can have it if you really want with __conversion()
e.g. If you need UInt8 and Int be able to convert from Double
extension Double {
func __conversion() -> UInt8 { return UInt8(self) }
func __conversion() -> Int { return Int(self) }
// add more if you need to
}
xcrun swift
Welcome to Swift! Type :help for assistance.
1> extension Double {
2. func __conversion() -> UInt8 { return UInt8(self) }
3. }
4> var d = 1.0
d: Double = 1
5> var u8 : UInt8 = d
u8: UInt8 = 1
6>
Note: I won't put this in my production code. I only want to point out it if possible but not recommending it.
using bridgeToObjectiveC() method you can call the methods provided in Objective - C to convert from one primitive data type to another for e.g.
variable_name.bridgeToObjectiveC().intValue
will convert that variable named variable_name to integer
Implicit conversion is possible but with literals only and some conversions are available from the box e.g. Int -> Double:
let a = 3 // Int
let b = 100.5 // Double
// Doesn't work with variables
let c = a * b // Error: Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
// But this works, because Int(3) literal converts to Double(3.0) implicitly
let d = 3 * b // 301.5
If you want to make backward conversion Double -> Int you should extend Int with ExpressibleByFloatLiteral:
extension Int: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.init(value)
}
}
// Double(100.5) converts to Int(100)
let e = a * 100.5 // 300
Even more it's possible to implicitly convert to any type from literals, for instance String -> URLRequest:
extension URLRequest: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(url: URL(string: value)!)
}
}
let request: URLRequest = "https://www.google.com"
is there any way to get absolute value from an integer?
for example
-8
to
8
I already tried to use UInt() assuming it will convert the Int to unsigned value but it didn't work.
The standard abs() function works great here:
let c = -8
print(abs(c))
// 8
With Swift 5, you may use one of the two following ways in order to convert an integer to its absolute value.
#1. Get absolute value of an Int from magnitude property
Int has a magnitude property. magnitude has the following declaration:
var magnitude: UInt { get }
For any numeric value x, x.magnitude is the absolute value of x.
The following code snippet shows how to use magnitude property in order to get the absolute value on an Int instance:
let value = -5
print(value.magnitude) // prints: 5
#2. Get absolute value of an Int from abs(_:) method
Swift has a global numeric function called abs(_:) method. abs(_:) has the following declaration:
func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
Returns the absolute value of the given number.
The following code snippet shows how to use abs(_:) global function in order to get the absolute value on an Int instance:
let value = -5
print(abs(value)) // prints: 5
If you want to force a number to change or keep it positive.
Here is the way:
abs() for int
fabs() for double
fabsf() for float
If you want to get absolute value from a double or Int, use fabs func:
var c = -12.09
print(fabs(c)) // 12.09
c = -6
print(fabs(c)) // 6