Reputation: 2001
Completing some old HackerRank challenges.
Some of these appear to be broken - for example "Fair Rations" gives us the following function signature (note: The capital for the parameter is not my fault, it is not changeable within this context.
func fairRations(B: [Int]) -> Int {
// Enter code answer code here
}
Now the problem test cases (the details of the problem are not important here) require that we return an
Int
(i.e. 4) for some test cases, and a
String
(i.e. "NO") for other tests.
So I need to return either a String, or an Int depending upon my answers. I've tried to return an enum, but I can't make any changes to the HackerRank tests - also returning any
like:
func fairRations(B: [Int]) -> Any {
// Enter code answer code here
}
will not work as Any is not implicitly convertible to either a String or an Int.
The HackerRank problem is here: https://www.hackerrank.com/challenges/fair-rations/problem
To clarify in response to Joakim Danielson, the problem description implies that you can output "NO" to the console, but that is not actually true (see screenshot below).
Is it possible to have a function that returns both a String and an Int in Swift?
Upvotes: 1
Views: 442
Reputation: 271070
Just change the function to return a String
. Keep in mind that integers can be represented as a string as well. The string "4" represents the number 4.
I changed the function to this in hacker rank:
func fairRations(B: [Int]) -> String {
return "4"
}
And it passed this test:
Basically,
x
, just return x.description
"NO"
.Both of the above values are strings.
Returning a String
here works because the test calls the String(...)
initialiser. And if you pass a string to that, it will still create the same string you passed in.
EDIT:
I tried editing the client code and it works. You can just return a Int?
and do this:
if let result = fairRations(B: B) {
fileHandle.write(String(result).data(using: .utf8)!)
} else {
fileHandle.write("NO".data(using: .utf8)!)
}
Upvotes: 1