Jay Patel
Jay Patel

Reputation: 47

How to convert NSString to Float

IBAction func numberPressed(sender: AnyObject) {
  if isTyping == false {
    firstNumber = (sender.currentTitle as NSString).floatValue
    displayLabel.text = "\(firstNumber)"
  }

Showing error:

Can not convert the expression's type '()' to type 'NSString'

Upvotes: 0

Views: 252

Answers (1)

Duncan C
Duncan C

Reputation: 131481

In your code sender is the anonymous type AnyObject. When you create an IBAction you have the option to change the type of Sender to the actual type of the control that triggers the action (usually a UIButton). I suggest changing the type of the sender to the correct type.

Failing that you will need to cast the type to your sender's type, which is a little bit risky.

let senderAsButton = sender as UIButton

That will crash at runtime of sender is not a UIButton. Thus it's better to fix the definition of the IBAction method signature.

Edit:

Another issue is that the UIButton method currentTitle returns an optional. You have to unwrap it:

firstNumber = (sender.currentTitle! as NSString).floatValue

Note that that code will crash if sender.currentTitle is nil. It would be safer to write it like this:

if let currentTitle = sender.currentTitle as NSString
{
  firstNumber = currentTitle.floatValue
}

Upvotes: 1

Related Questions