How to convert from UITextField to Decimal - swift

I have a UITextField with a decimal pad. I try to do some math with the value in it but I can't figure it out.
To get a string as an int, I do this:
let number:Int? = Int(self.number.text!)
...which works.
But I don't understand why I can't do the following for decimal:
let decimalNumber:Decimal? = Int(self.decimalNumber.text!)
I get an error message:
Cannot invoke initializer for type 'Decimal' with an argument of list of type '(String)'
With my javascript knowledge, I find it hard to deal with values coming from a field on iOS :)

Related

Casting an Int as a String from a Realm result Swift

I am asking this hesitantly as I know this is probably a dumb question.
I am returning a Realm result and then have gone ahead and tried to cast it to a String as normal (to put in a text label).
However I'm getting an error 'init' has been renamed to 'init(describing:)'.
When I try use the describing method instead, the label prints "Optional" inside it which obviously isn't what I want.
Is there a reason I can't use :
previousTimeLabel.text = String(lastRecord?.time)
I'm sure I've done this before and it's been fine, am I missing something? (lastRecord.time is an Int).
I've checked the answer here about Interpolation Swift String Interpolation displaying optional? and tried changing to something like this :
if let previousRounds = String(lastRecord?.rounds) {
previousRoundsLabel.text = previousRounds
}
but get the same error + Initializer for conditional binding must have Optional type, not 'String'
The issue isn't String(lastRecord?.time) being Optional. The issue is lastRecord being Optional, so you have to unwrap lastRecord, not the return value of String(lastRecord?.time).
if let lastRecord = lastRecord {
previousRoundsLabel.text = "\(lastRecord.time)"
}
To summarize Dávid Pásztor's answer, here's a way you can fix it:
previousTimeLabel.text = String(lastRecord?.time ?? 0)
This may not be the best way for your application. The point Dávid was making is that you need to deal with lastRecord possibly being nil before trying to pass its time Int into the String initializer. So the above is one simple way to do that, if you're ok with having "0" string as your previousTimeLabel's text if there was no lastRecord.

Swift - Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'

Not really understanding why this isn't working. I'm pretty new to the Swift world.
The error I'm getting is Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'
Could anyone help me understand why I'm getting this error? Do I need to convert the String to a Double or is there something else I'm totally missing? Again I'm new to Swift.
Do I need to convert the String to a Double?
Yes, that's basically it.
You must declare first a variable to accumulate all the inputs:
var inputs = [Double]()
Observe that I'm declaring an array of Double because that's what we are interested in.
Then, each time you ask the input, convert the obtained String to Double and store it in your array:
print("Please enter a temperature\t", terminator: "")
var message : String = readLine()!
let value : Double = Double(message)!
inputs.append(value)
Finally, check all the accumulated values in inputs (you got this part right):
for value in inputs {
// value is already a Double
if value >= 80 {
message = "hot!"
}
// etc.
}
I suggest researching how to convert to Double with error checking (i.e. how to detect "100 hot!" and ignore it because can't be converted).
Also, consider using a loop to read the values.

Swift 3 cast UITextField to Int

I'm receiving a compiler error and I'm not really sure why. I'm sure there is a simple answer for this. I have a core data attribute I'm trying to assign before saving. In my Core Data Property file it's defined as this:
#NSManaged public var age: Int32
I am using a UIPicker to select it and put it into an inputView. That works fine, so ageTextField: UITextField! holds the value. As I try to assign this to the CoreData object just before saving I get the following
person.age = ageTextField.text -> Cannot assign String? to Int32.
Ok, I understand that, so I cast it
person.age = Int(ageTextField.text) -> Value of Optional String not unwrapped...
Ok, I get that, so I unwrapped it, it asks to unwrap again and I agree:
person.age = Int(ageTextField.text!)! -> Type of expression is ambiguous without more context
I'm not sure what is wrong here, just looking over some old Swift 2 code of mine and this worked. This is my first code with Swift 3 though.
That compiler error is obscure at best and misleading at worst. Change your cast to Int32:
person.age = Int32(ageTextField.text!)!
Also: unless you are absolutely sure that the user will always enter a valid number into the textfield, use optional binding instead of force unwrap:
if let text = ageTextField.text,
let age = Int32(text)
{
person.age = age
}
The immediate issue is the use of the wrong type. Use Int32, not Int. But even once that is fixed, you have lots of other issues.
You should safely unwrap the text and then the attempt to convert the string to an integer.
if let text = ageTextField.text, let num = Int32(text) {
person.age = num
}
The use of all of those ! will cause a crash if the text is nil or it contains a value that isn't a valid number. Always use safe unwrapping.
Just make sure to unwrap the optional before convert. Make your code safe.

Swift 2 using Parse : could not cast value of type '__NSArrayM' to 'NSNumber'

i try to modify an array in parse using swift 2, i don't have anny issue when i build the app but when i touch the button linked to the action i got this error (see below). I already tried to modify my code using kcurrentUser or different things like that but i always get the same issue ..
Could not cast value of type '__NSArrayM' (0x10f4d58d8) to 'NSNumber' (0x10f8c7278).(lldb)
Here's my code:
PFUser.currentUser().addObject([kCurrentUser.objectForKey("Participations") as! Int + 1], forKey: "Participations")
The object for your key "Participation" is an array. You are trying to cast it as an Int.

Cannot assign value of type 'String' to type 'NSTimeInterval' (aka 'Double')

I'm trying to set my sliders value to the sounds currentValue but then I get this error:
Cannot assign value of type 'String' to type 'NSTimeInterval' (aka 'Double')
I am kind of new to Xcode and errors so I don't really know how to solve this problem but I tried to delete the string part but that did not work.
#IBAction func time(sender: UISlider) {
var timeValue:String = String(Int(sender.value)) sound!.currentTime = timeValue
}
timeValue is a String and currentTime most likely is a NSTimeInterval. You can't assign string to NSTimeInterval. Use Double(sender.value) instead. Also, I would suggest that you do not combine so many operations on one line, especially if you are new to programming or Swift. If you get an error, you don't easily see if the problem was with conversion to String, to Int, if your sound variable was nil or what else is going on.