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
Related
Is it save to use cast to int instead of Math.floor to convert float / double values to integers?
var scale = 1.5;
int foo1 = (int)scale;
int foo2 = Math.floor(scale);
In this case both Case to Int and Math.floor will return integer value. If x=3.5 then both function will return 3 in output. Cast to int is a function to convert variable of any datatype to integer type, on the other hand Math.floor function will only floor the decimal number to integer not converting datatype. But result will be different in case of negative values because Cast to Int approaches to zero and Math.floor approaches to negative infinity. So in that perspective if you are working on real numbers (both positive and negative) then it is unsafe to use Cast to Int instead of Math.floor to get precise output.
As Vala code is translated into C, this is the same question as Cast to int vs floor
TL;DR: yes it is safe but the result of Math.floor and float/double casting are different when negative numbers are given.
Note that Math.floor is part of the GLib library and thus is not available in the POSIX profile.
weight is a field (Number in Firestore), set as 100.
int weight = json['weight'];
double weight = json['weight'];
int weight works fine, returns 100 as expected, but double weight crashes (Object.noSuchMethod exception) rather than returning 100.0, which is what I expected.
However, the following works:
num weight = json['weight'];
num.toDouble();
When parsing 100 from Firestore (which actually does not support a "number type", but converts it), it will by standard be parsed to an int.
Dart does not automatically "smartly" cast those types. In fact, you cannot cast an int to a double, which is the problem you are facing. If it were possible, your code would just work fine.
Parsing
Instead, you can parse it yourself:
double weight = json['weight'].toDouble();
Casting
What also works, is parsing the JSON to a num and then assigning it to a double, which will cast num to double.
double weight = json['weight'] as num;
This seems a bit odd at first and in fact the Dart Analysis tool (which is e.g. built in into the Dart plugin for VS Code and IntelliJ) will mark it as an "unnecessary cast", which it is not.
double a = 100; // this will not compile
double b = 100 as num; // this will compile, but is still marked as an "unnecessary cast"
double b = 100 as num compiles because num is the super class of double and Dart casts super to sub types even without explicit casts.
An explicit cast would be the follwing:
double a = 100 as double; // does not compile because int is not the super class of double
double b = (100 as num) as double; // compiles, you can also omit the double cast
Here is a nice read about "Types and casting in Dart".
Explanation
What happened to you is the following:
double weight;
weight = 100; // cannot compile because 100 is considered an int
// is the same as
weight = 100 as double; // which cannot work as I explained above
// Dart adds those casts automatically
You can do it in one line:
double weight = (json['weight'] as num).toDouble();
You can Parse the data Like given below:
Here document is a Map<String,dynamic>
double opening = double.tryParse(document['opening'].toString());
In Dart, int and double are separate types, both subtypes of num.
There is no automatic conversion between number types. If you write:
num n = 100;
double d = n;
you will get a run-time error. Dart's static type system allows unsafe down-casts, so the unsafe assignment of n to d (unsafe because not all num values are double values) is treated implicitly as:
num n = 100;
double d = n as double;
The as double checks that the value is actually a double (or null), and throws if it isn't. If that check succeeds, then it can safely assign the value to d since it is known to match the variable's type.
That's what's happening here. The actual value of json['weight'] (likely with static type Object or dynamic) is the int object with value 100. Assigning that to int works. Assigning it to num works. Assigning it to double throws.
The Dart JSON parser parses numbers as integers if they have no decimal or exponent parts (0.0 is a double, 0e0 is a double, 0 is an integer). That's very convenient in most cases, but occasionally annoying in cases like yours where you want a double, but the code creating the JSON didn't write it as a double.
In cases like that, you just have to write .toDouble() on the values when you extract them. That's a no-op on actual doubles.
As a side note, Dart compiled to JavaScript represents all numbers as the JavaScript Number type, which means that all numbers are doubles. In JS compiled code, all integers can be assigned to double without conversion. That will not work when the code is run on a non-JS implementation, like Flutter, Dart VM/server or ahead-of-time compilation for iOS, so don't depend on it, or your code will not be portable.
Simply convert int to double like this
int a = 10;
double b = a + 0.0;
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)
I have converted a String to an Int by by using toInt(). I then tried multiplying it by 0.01, but I get an error that says Could not find an overload for '*' that accepts the supplied argument. Here is my code:
var str: Int = 0
var pennyCount = 0.00
str = pennyTextField.text.toInt()!
pennyCount = str * 0.01
From reading other posts it seems that the answer has to do with the type. For example if the type is set as an Integer then it gets a similar error. I have tried changing the type to an Int, but that doesn't seem to solve the problem.
I have also tried setting the type for 'str' and 'pennyCount' as Floats and Doubles and all combinations of Floats, Doubles, and Ints. My guess is the the problem has to do with toInt() function's conversion of a String to an Integer.
Could someone help clarify what the issue may be?
Swift seems to be fairly picky about implied type casting, so in your example you're multiplying str (an Integer) by 0.01 (a Double) so to resolve the error, you'll need to cast it like this:
var str: Int = 0
var pennyCount = 0.00
str = pennyTextField.text.toInt()!
pennyCount = Double(str) * 0.01
I want to understand how to access the "struct" type of Int. When I cmd-clicked Int it took me to this class, i want to find out what is the maximum value this can hold. Is there a way to pull from one of this properties ?. what is max and min in this structure ?
struct Int : SignedInteger {
var value: Builtin.Word
init()
init(_ v: Builtin.Word)
init(_ value: Int)
static func convertFromIntegerLiteral(value: Int) -> Int
typealias ArrayBoundType = Int
func getArrayBoundValue() -> Int
static var max: Int { get }
static var min: Int { get }
}
“You can access the minimum and maximum values of each integer type with its min and max properties:
let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8
The values of these properties are of the appropriate-sized number type (such as UInt8 in the example above) and can therefore be used in expressions alongside other values of the same type.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/in/jEUH0.
Try this in Swift 3:
let value = Int.max
You can access the minimum and maximum values of each integer type with its min and max properties:
let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8
The values of these properties are of the appropriate-sized number type (such as UInt8 in the example above) and can therefore be used in expressions alongside other values of the same type.
from: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
You can access these as static properties as suggested in other answers.
I see in some comments people are wondering why you can't access them as instance variables.
This is like asking "what is the max value of 5?" and expecting a sensible answer.
One of the main uses for these variables is guarding against integer overflows.
Something along the lines of "if I add something to this integer that makes it bigger than Int.max i.e. it triggers an overflow " and act accordingly.
More on how Apple address the issue of integer overflows here.