"Additional argument in call" error in Swift

Before anyone sends me to see the previous post, know that I looked a ton and my newbie status prevented me from implementing previous answers that may or may not be relevant.

I am studying iOS code with Swift and as an exercise I am creating a simple app to convert miles to km. The following code works flawlessly:

// convert miles from string to float
var miles = (textfieldMiles.text as NSString).floatValue

// calculate kilometers
var kilometers = miles * 1.609344

// determine terminology
var termMiles = "mile"
if (miles != 1.00) {
    termMiles = termMiles + "s"
}
var termKilometers = "kilometer"
if (kilometers != 1.00) {
    termKilometers = termKilometers + "s"
}

// display results
labelMain.text = "\(miles) \(termMiles) = \(kilometers) \(termKilometers)"

      

I want to display the resulting miles / km with two digits after the decimal, so I implemented the following:

// format numbers
miles = NSString(format:"%.2f", miles)

      

This gives me an "extra argument in call" error. As far as I can tell, this is because my float in "miles" cannot use NSString for some reason. I have no idea how to fix this, and while it seems to me that some of the previous answers should probably be helpful, I do not have enough history knowledge to understand them. Can some soul explain what the solution is and for bonus points why the solution works?

+3


source to share


1 answer


Short, straightforward answer

Oh! This is a case of an incorrect compiler warning. The real problem is when you are trying to assign a value to String

a type variable Float

.

Try something like this: let milesString = NSString(format: "%.2f", miles)

and you will see that it works as expected. You cannot reuse miles

like NSString

after you first declare it Float

.



Longer, Rambling's answer

When you first declared your variable miles

, the Swift compiler assumed it was of type Float

because it returns (textfieldMiles.text as NSString).floatValue

. Then, when you tried to assign to NSString

the same variable, the compiler gave up, because Swift does not imply type conversion for you. This is not an oversight in compiler design, but it is actually a very useful function - type conversion happens much more often by accident than intentional, and if you already understand that you want to explicitly convert a type, you can just write the conversion syntax while you are at German

+2


source







All Articles