I want to multiply a text field by a multiplier, but I keep getting the error below. Can anyone help? Using Swift.
Binary operator '*' cannot be applied to operands of type 'Int?' and 'Double'
var Number1 = Int(weight.text!)
let lidocainemult = (1.5)
var lidoresult = Number1 * lidocainemult
lidocaine.text = NSString(format:"%d",lidoresult)as String;
You're going to have to convert your variables into the same type first. Here Double would make the most sense, since there would be no loss of information (unlike rounding to produce an Int!).
var Number1 = Double(weight.text!)
let lidocainemult = (1.5)
var lidoresult = Number1 * lidocainemult
lidocaine.text = NSString(format:"%d",lidoresult)as String;
You must convert Number1 to a Double, the operands must be of same type.
var Number1 = Double(weight.text!)
Related
let totalPrice: Double = price * value
var money: Double = 0
for totalPrice in dataArray {
money = money + totalPrice
}
Unable to assign binary operator '+'
How is "dataArray" declared?
Is it a [AnyObject] or [Double]
If it's the former, you'll need to cast it as a double by using:
guard let price = totalPrice as? Double else { continue }
money = money + totalPrice
totalPrice is type of Element. I think there should be some kind of amount which is typed of Double don't you?
Also when you are dealing with currency data check NSDecimalNumber. Double will lose significant numbers.
The problem is that your dataArray is array of type AnyObject. If it really contain doubles, you can iterate like this:
for totalPrice in dataArray as! [Double] {
money = money + totalPrice
}
I am using Xcode playground to downcast in swift. Typecasting would normally allow me to convert a type to derived type using As operator in swift. But it gives me error while i try to typecast var a as Double,String. Thanks in advance!!
var a = 1
var b = a as Int
var c = a as Double
var d = a as String
You cannot cast it to each other because they do not relate. You can only cast types that are related like UILabel and UIView or [AnyObject] and [String]. Casting an Int to a Double would be like trying to cast a CGPoint to a CGSize
So to change for example an Int to a Double you have to make a new Double of that Int by doing Double(Int).
This applies to all numeric types like UInt Int64 Float CGFloat etc.
Try this:
var a = 1
var b = Int(a)
var c = Double(a)
var d = String(a)
Cast as Int works, because a is Int
You should do it like this:
var c = Double(a)
var d = toString(a) //or String(a)
An issue here to me that if i use parse string for the result of calculator program for instance,
4.5 * 5.0 = 22.5
how can I use splitting here to depart decimal part from result?
Assuming you're working with strings only :
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
Use modf to extract decimal part from result.
Objective-C :
double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(#"%f",fractional);
Swift :
var integral:Double = 22.5;
let fractional:Double = modf(integral,&integral);
println(fractional);
Want only interger part from double of float
Want only integer value from double then
let integerValue:Int = Int(integral)
println(integerValue)
Want only integer value from float then
let integerValue:Float = Float(integral)
println(integerValue)
I've looked at the answers for converting int's to floats and other similar answers but they don't do exactly what I want.
I'm trying to create a basic program that takes a number does some different calculations onto it and the results of those calculations are added together at the end.
For one of those calculations I created a segmented controller with the 3 different values below
var myValues: [Double] = [0.00, 1.00, 1.50]
var myValue = [myValuesSegmentedController.selectedSegmentIndex]
then when one of those values is picked, it's added to the final value. All the values added together are Doubles to 2 decimal places.
var totalAmount = valueA + valueB + valueC + myValue
the problem I'm having is that swift won't let me add "myValue" to those final calculations. It gives me the error:
Swift Compiler Error. Cannot invoke '+' with an argument list of type '($T7, #lvalue [int])'
What do I need to do to change that value to a Double? Or what can I do to get a similar result?
You can cast it with Double() like this
var totalAmount = valueA + valueB + valueC + Double(myValue)
The problem is you are trying to add an array instead of an Int, so You don't even need to convert anything, considering that all of your values are already Doubles and your index actually has to be an Int. So
let myValues = [0.00, 1.00, 1.50]
let myValue = [myValuesSegmentedController.selectedSegmentIndex] // your mistake is here, you are creating one array of integers with only one element(your index)
The correct would be something like these:
let myValues = [0.00, 1.00, 1.50]
let totalAmount = myValues.reduce(0, combine: +) + myValues[myValuesSegmentedController.selectedSegmentIndex]
Put this in a playground:
var myValues: [Double] = [0.00, 1.00, 1.50]
let valueA = 1
let valueB = 2
let valueC = 3
var totalAmount = Double(valueA + valueB + valueC) + myValues[2]
println(totalAmount) //output is 7.5
valueA/B/C are all inferred to be Int.
totalAmount is inferred to be a Double
To convert a float to an integer in Swift. Basic casting like this does not work because these vars are not primitives, unlike floats and ints in Objective-C:
var float:Float = 2.2
var integer:Int = float as Float
Using swift and Xcode 6, I'm trying to return a value calculated based on content of few UITextFields.
I have declared variables
var Number1 = Field1.text.toInt()
var Number2 = Field2.text.toInt()
var Duration = Number1*Number2
Mylabel.text = String ("\(Duration)")
The idea is to capture duration from few UI Fields and based on calculation of those values assign that to a variable as well as display it on a label.
In line: var Duration = Number1*Number2
Challenge is that I have is that when performing multiplication Xcode highlight error: Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
The toInt() method returns an optional value because the string it is trying to convert may not contain a proper value. For instance, these strings will be converted to nil: "house", "3.7","" (empty string).
Because the values may be nil, toInt() returns an optional Int which is the type Int?. You can't use that value without unwrapping it first. That is why you are getting the error message. Here are two safe ways to handle this:
You need to decide what you want to do when a value can't be converted. If you just want to use 0 in that case, then use the nil coalescing operator (??) like so:
let number1 = field1.text.toInt() ?? 0
// number1 now has the unwrapped Int from field1 or 0 if it couldn't be converted
let number2 = field2.text.toInt() ?? 0
// number2 now has the unwrapped Int from field2 or 0 if it couldn't be converted
let duration = number1 * number2
mylabel.text = "\(duration)"
If you want your program to do nothing unless both fields have valid values:
if let number1 = field1.text.toInt() {
// if we get here, number1 contains the valid unwrapped Int from field1
if let number2 = field2.text.toInt() {
// if we get here, number2 contains the valid unwrapped Int from field2
let duration = number1 * number2
mylabel.text = "\(duration)"
}
}
So, what did the error message mean when it said did you mean to use a !. You can unwrap an optional value by adding a ! to the end, but you must be absolutely sure the value is not nil first or your app will crash. So you could also do it this way:
if number1 != nil && number2 != nil {
let duration = number1! * number2!
mylabel.text = "\(duration)"
}
Get the value of textFields in var, multiply them, and then set the value of label. Try this:
var Number1 = Field1.text.toInt()
var Number2 = Field2.text.toInt()
var Duration = Number1 * Number2
Mylabel.text = NSString(format:"%d",Duration!)as String;
Hope this helps.. :)