简体   繁体   中英

“Extra argument in call” error in Swift

Before anyone sends me to look at a previous post, know that I've looked at a ton, and my novice status has prevented me from implementing previous answers that may or may not be relevant.

I'm learning to code for iOS with Swift, and as an exercise I'm building a simple app to convert miles to km. The following code is working flawlessly so far:

// 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 show the resulting miles/kms with only two digits following the decimal, so I implemented the following:

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

This gives me an error "extra argument in call". As best I can tell, this is because my floating value in "miles" cannot use NSString, for some reason. I have no idea how to fix this, and while I feel like some of the previous answers probably should be helpful, I don't have enough background knowledge yet to understand them. Can some kind soul explain what the solution is, and for bonus points, why the solution works?

Short, Direct Answer

Ah! It's a case of an incorrect compiler warning. The real issue is that you're attempting to assign a String value to a variable of type Float .

Try something like this: let milesString = NSString(format: "%.2f", miles) and you'll see that it works as expected—you can't reuse miles as an NSString after first declaring it to be a Float .

Longer, Rambling Answer

When you first declared your miles variable, the Swift compiler inferred it to be of type Float because that's what (textfieldMiles.text as NSString).floatValue returns. Then, when you attempted to assign an NSString to that very same variable, the compiler gave up because Swift doesn't implicitly convert types of variables for you. This isn't an oversight in the design of the compiler, it's actually a very useful feature—converting types happens a lot more often by accident than intentionally, and if you're already cognizing about wanting to explicitly convert a type, you might as well just write some conversion syntax while you're at it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM