Swift return different Types from a function












0















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).



enter image description here



Is it possible to have a function that returns both a String and an Int in Swift?










share|improve this question

























  • return value will be Int for Successful test cases and String for Failure right?

    – hardik parmar
    Nov 20 '18 at 6:21











  • So, what's the exact context here? fairRations(B: [Int]) should return an Int, fairRations(B: [String]) should return a String, or should fairRations(B: [Int]) also occasionally return a string?

    – Sander Saelmans
    Nov 20 '18 at 6:23













  • @hardikparmar Indeed. The logic defines whether the input is a success or not. I have some code that works, but returns 0 for "Failure" but clearly this will not past any test cases!

    – stevenpcurtis
    Nov 20 '18 at 6:23













  • @SanderSaelmans The Signature is func fairRations(B: [Int]) which I would like to try to return EITHER a String or an Int depending upon my internal logic. I cannot change the function that uses this signature

    – stevenpcurtis
    Nov 20 '18 at 6:25











  • can you return a tuple like (String, Int)? will that work for your problem statement?

    – hardik parmar
    Nov 20 '18 at 6:30
















0















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).



enter image description here



Is it possible to have a function that returns both a String and an Int in Swift?










share|improve this question

























  • return value will be Int for Successful test cases and String for Failure right?

    – hardik parmar
    Nov 20 '18 at 6:21











  • So, what's the exact context here? fairRations(B: [Int]) should return an Int, fairRations(B: [String]) should return a String, or should fairRations(B: [Int]) also occasionally return a string?

    – Sander Saelmans
    Nov 20 '18 at 6:23













  • @hardikparmar Indeed. The logic defines whether the input is a success or not. I have some code that works, but returns 0 for "Failure" but clearly this will not past any test cases!

    – stevenpcurtis
    Nov 20 '18 at 6:23













  • @SanderSaelmans The Signature is func fairRations(B: [Int]) which I would like to try to return EITHER a String or an Int depending upon my internal logic. I cannot change the function that uses this signature

    – stevenpcurtis
    Nov 20 '18 at 6:25











  • can you return a tuple like (String, Int)? will that work for your problem statement?

    – hardik parmar
    Nov 20 '18 at 6:30














0












0








0








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).



enter image description here



Is it possible to have a function that returns both a String and an Int in Swift?










share|improve this question
















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).



enter image description here



Is it possible to have a function that returns both a String and an Int in Swift?







swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 6:41







stevenpcurtis

















asked Nov 20 '18 at 6:18









stevenpcurtisstevenpcurtis

729820




729820













  • return value will be Int for Successful test cases and String for Failure right?

    – hardik parmar
    Nov 20 '18 at 6:21











  • So, what's the exact context here? fairRations(B: [Int]) should return an Int, fairRations(B: [String]) should return a String, or should fairRations(B: [Int]) also occasionally return a string?

    – Sander Saelmans
    Nov 20 '18 at 6:23













  • @hardikparmar Indeed. The logic defines whether the input is a success or not. I have some code that works, but returns 0 for "Failure" but clearly this will not past any test cases!

    – stevenpcurtis
    Nov 20 '18 at 6:23













  • @SanderSaelmans The Signature is func fairRations(B: [Int]) which I would like to try to return EITHER a String or an Int depending upon my internal logic. I cannot change the function that uses this signature

    – stevenpcurtis
    Nov 20 '18 at 6:25











  • can you return a tuple like (String, Int)? will that work for your problem statement?

    – hardik parmar
    Nov 20 '18 at 6:30



















  • return value will be Int for Successful test cases and String for Failure right?

    – hardik parmar
    Nov 20 '18 at 6:21











  • So, what's the exact context here? fairRations(B: [Int]) should return an Int, fairRations(B: [String]) should return a String, or should fairRations(B: [Int]) also occasionally return a string?

    – Sander Saelmans
    Nov 20 '18 at 6:23













  • @hardikparmar Indeed. The logic defines whether the input is a success or not. I have some code that works, but returns 0 for "Failure" but clearly this will not past any test cases!

    – stevenpcurtis
    Nov 20 '18 at 6:23













  • @SanderSaelmans The Signature is func fairRations(B: [Int]) which I would like to try to return EITHER a String or an Int depending upon my internal logic. I cannot change the function that uses this signature

    – stevenpcurtis
    Nov 20 '18 at 6:25











  • can you return a tuple like (String, Int)? will that work for your problem statement?

    – hardik parmar
    Nov 20 '18 at 6:30

















return value will be Int for Successful test cases and String for Failure right?

– hardik parmar
Nov 20 '18 at 6:21





return value will be Int for Successful test cases and String for Failure right?

– hardik parmar
Nov 20 '18 at 6:21













So, what's the exact context here? fairRations(B: [Int]) should return an Int, fairRations(B: [String]) should return a String, or should fairRations(B: [Int]) also occasionally return a string?

– Sander Saelmans
Nov 20 '18 at 6:23







So, what's the exact context here? fairRations(B: [Int]) should return an Int, fairRations(B: [String]) should return a String, or should fairRations(B: [Int]) also occasionally return a string?

– Sander Saelmans
Nov 20 '18 at 6:23















@hardikparmar Indeed. The logic defines whether the input is a success or not. I have some code that works, but returns 0 for "Failure" but clearly this will not past any test cases!

– stevenpcurtis
Nov 20 '18 at 6:23







@hardikparmar Indeed. The logic defines whether the input is a success or not. I have some code that works, but returns 0 for "Failure" but clearly this will not past any test cases!

– stevenpcurtis
Nov 20 '18 at 6:23















@SanderSaelmans The Signature is func fairRations(B: [Int]) which I would like to try to return EITHER a String or an Int depending upon my internal logic. I cannot change the function that uses this signature

– stevenpcurtis
Nov 20 '18 at 6:25





@SanderSaelmans The Signature is func fairRations(B: [Int]) which I would like to try to return EITHER a String or an Int depending upon my internal logic. I cannot change the function that uses this signature

– stevenpcurtis
Nov 20 '18 at 6:25













can you return a tuple like (String, Int)? will that work for your problem statement?

– hardik parmar
Nov 20 '18 at 6:30





can you return a tuple like (String, Int)? will that work for your problem statement?

– hardik parmar
Nov 20 '18 at 6:30












1 Answer
1






active

oldest

votes


















1














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:



enter image description here



Basically,




  • If you want to return an integer x, just return x.description

  • If you want to return NO, just return "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)!)
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387295%2fswift-return-different-types-from-a-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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:



    enter image description here



    Basically,




    • If you want to return an integer x, just return x.description

    • If you want to return NO, just return "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)!)
    }





    share|improve this answer






























      1














      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:



      enter image description here



      Basically,




      • If you want to return an integer x, just return x.description

      • If you want to return NO, just return "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)!)
      }





      share|improve this answer




























        1












        1








        1







        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:



        enter image description here



        Basically,




        • If you want to return an integer x, just return x.description

        • If you want to return NO, just return "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)!)
        }





        share|improve this answer















        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:



        enter image description here



        Basically,




        • If you want to return an integer x, just return x.description

        • If you want to return NO, just return "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)!)
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 20 '18 at 6:51

























        answered Nov 20 '18 at 6:44









        SweeperSweeper

        67.2k1073139




        67.2k1073139
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387295%2fswift-return-different-types-from-a-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Can I use Tabulator js library in my java Spring + Thymeleaf project?