How do you format floats into strings in Swift 5? - swift

I am trying to format a float into a string with a set number of digits. All the examples I have seen use something like this:
let thisString = String(format: "%2.4f" , 3.14159262)
However, when I try this I get:
Argument labels '(format:, _:)' do not match any available overloads
. Like it doesn't even recognize "format" as a valid way to initialize a string. I am using Swift 5 on Xcode 10.2 on Mojave, if that makes a difference. Am I missing some framework or something? Did the initializer change?

Your code should be working correctly. Can you please try the following:
import Foundation
let firstString = String(format: "%2.4f", arguments: [3.14159262])
print(firstString)
let secondString = String(format: "%2.4f", 3.14159262)
print(secondString)
I have this code running fine in a playground using Swift 5.
Removing the Foundation import gives the same error you described in your question.

Related

Evaluating a string in swift

In swift, in Xcode, I am making a calculator app. The app was all working fine but then I realised that the function to solve maths was not working. I had used the function shown in this question. It can solve most problems but when you involve decimal places:e.g. "3/2" you would expect it to return "1.5". It will return 1.0.
Here is the function I am using:
func mathsSolver(item: String) -> String {
let result = NSExpression(format: item).expressionValue(with: nil, context: nil) as! Double
return "\(result)"
}
You can call this function with:
print(mathsSolver(item: "3/2")) //this will print 1.0
Any Ideas?
You have to pass the double value so that you can get result 1.5
print(mathsSolver(item: "3.0/2.0"))
Above you are trying to pass Int value so that it is not giving you the proper result because integer division will always gives you the answer in integer.
Try:
NSExpression(format: "3.0 / 2.0");
this issue has plenty answears on stackoverflow. Check them out. ^_^
How to stop NSExpression from rounding
NSExpression 1/2
Its very popular problem. In swift wench you try to divide one Int number by another Int its automatically cleans up everything what must be after doth. For example if you want to divide 5/2 instead 2.5 you will get = 2. In you example swift has deleted everything after doth and instead 1.5 you got just 1.
To resolve this issue try to use Double or Float instead of Int and everything will be fine!

URL.init?(string: String) returns 'nil' when it shouldn't

I'm experiencing an issue with the Foundation struct URL's string initializer. I'll post some code from the repl below:
Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
Type :help for assistance.
1> import Foundation
2> let testString = "https://www.apple.com"
testString: String = "https://www.apple.com"
3> let testUrl1 = URL(string: testString)
testUrl1: URL? = nil
4> let testUrl2 = URL(string: "https://www.apple.com")
testUrl2: URL? = nil
I cannot think of why this is happening, if you look at the source for the initializer, located at https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/URL.swift#L495 you'll see this in the documentation:
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
As far as I can tell though, the string I am testing with is a valid URL and the initializer shouldn't be returning nil. I have tried this on two different Macs and in a freshly installed virtual machine, and have gotten the same result in all of them. macOS 10.15, Xcode 11.1. Anyone have any insight into what might be wrong?
It would appear to be a REPL issue and existed in 11.0, too. But if you print(testUrl1), you’ll see it really is set.

Why can't NSSpeechsynthesier's class method availableVoices be bridged to a Swift array of strings?

In Apple's Working with Cocoa Frameworks it reads as if the Foundation and Swift Foundation frameworks work together through bridging. However, I noticed that while attempting to use NSSpeechSynthesizer's class method availableVoices() it allows me to received an returned array of NSStrings but not Strings.
This compiles and runs just fine:
let voices = NSSpeechSynthesizer.availableVoices as [NSString]
print(voices)
However this won't compile:
let voicesTwo = NSSpeechSynthesizer.availableVoices as [String]
Why wouldn't this work if the voiceName documentation shows that VoiceName is a string property?
I see the term 'rawValue' in the VoiceName documentation so is the reasoning having anything to do with this being some sort of an enum?
It looks like NSSpeechSynthesizer.VoiceName is an Enum with a rawValue of String. That is not the same thing as being a string.
Try using
NSSpeechSynthesizer.availableVoices.map { $0.rawValue }

UIDevice.currentDevice().identifierForVendor!.UUIDString Swift 3 migration

I have the following code in swift 2
let deviceid = UIDevice.currentDevice().identifierForVendor!.UUIDString
This fails to compile. I tried following suggestions from the auto-fix in xCode and I came up with this.
let deviceid = UIDevice.currentDevice.identifierForVendor!.UUIDString
However it still does not compile. It says value of type 'UUID' has no member UUIDString'
My advice - for these kind of issues - get straight into a playground
let deviceid = UIDevice.current.identifierForVendor?.uuidString

Xcode 8.0 and Swift 3.0 conversion: Looking for explanation for a particular conversion error

I am a little confused about a conversion error.
I migrated my project form Swift 2.3 to Swift 3.0
func updateCelsiusLabel() {
if let value = celsiusValue {
//This was the original code (that worked but is) failing after migration
//due to: Argument labels do not match any available overloads
celsiusLabel.text = numberFormatter.string(from: NSNumber(value))
//This is my code trying to fix this issue and the project is now compiling
//and everything is fine
celsiusLabel.text = numberFormatter.string(from: value as NSNumber)
}
else { celsiusLabel.text = "???"
}
}
At first I thought that in Swift 3.0 the cast Type(value) was now forbidden, but I checked and I get absolutely no compiler warning. Can somebody tell me what the problem with NSNumber(value) is?
As far as I understand value as NSNumber and NSNumber(value) should be the same thing.
In Swift 3, NSNumber(value) won't work. Let's say that your value is an Int. In that case, you'd need NSNUmber(value: yourIntValue). In Swift 3, you must have the name of the first (and in this case the only) parameter in the function call. So, your usage of
value as NSNumber
works, but
NSNumber(value: yourNumberValue)
works too.
First of all I have taken some assumption here, I have assumed that -
numberFormatter = NSNumberFormatter() // Now it has been renamed to NumberFormatter
celsiusLabel.text I am taking text as optional string just for example you can use label.text for same.
After the above assumption please see below code which will work in Swift 3 -
var celsiusValue:Double?
var numberFormatter = NumberFormatter()
var text:String?
func updateCelsiusLabel() {
if let value = celsiusValue {
//This was the original code (that worked but is) failing after migration due to: Argument labels do not match any available overloads
text = numberFormatter.string(from: NSNumber(value: value))!
}
else {
text = "???"
}
}
Hope it help feel free to leave comment in case you have any doubt.