FizzBuzz with more parameters in SwiftUltimate FizzBuzzShort Java FizzBuzz using recursion and parametersIs this FizzBuzz Swift-y?Down with FizzBuzz… LOLSwift complexities with DictionaryUltimate FizzBuzzFizzBuzz in Swift 2FizzBuzz in accordance with standardsFizzBuzz with debugging outputNavigation controller in SwiftMVVM in Swift iOS

What would it take to get a message to another star?

Finding the shaded region

How can I shoot a bow using strength instead of dexterity?

How to prevent criminal gangs from making/buying guns?

Do I have to cite common CS algorithms?

How would armour (and combat) change if the fighter didn't need to actually wear it?

Units of measurement, especially length, when body parts vary in size among races

What is the most difficult concept to grasp in Calculus 1?

How can I find an old paper when the usual methods fail?

Why does Japan use the same type of AC power outlet as the US?

Attacking the Hydra

Boss wants me to ignore a software API license

How do I ask for 2-3 days per week remote work in a job interview?

Prestidigitation to replace bathing and washing clothes worn?

What are the odds of rolling specific ability score totals in D&D?

Are there really no countries that protect Freedom of Speech as the United States does?

What is the hottest thing in the universe?

Escape Velocity - Won't the orbital path just become larger with higher initial velocity?

What unique challenges/limitations will I face if I start a career as a pilot at 45 years old?

How does the Athlete Feat affect the Ravnica Centaur playable race?

Is there a way to proportionalize fixed costs in a MILP?

Do beef farmed pastures net remove carbon emissions?

How would you translate this? バタコチーズライス

What should I do if actually I found a serious flaw in someone's PhD thesis and an article derived from that PhD thesis?



FizzBuzz with more parameters in Swift


Ultimate FizzBuzzShort Java FizzBuzz using recursion and parametersIs this FizzBuzz Swift-y?Down with FizzBuzz… LOLSwift complexities with DictionaryUltimate FizzBuzzFizzBuzz in Swift 2FizzBuzz in accordance with standardsFizzBuzz with debugging outputNavigation controller in SwiftMVVM in Swift iOS






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3 and 5).



I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz return values.



I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.



How can I improve it?



func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String 
var result: String = ""

for key in responsesByMultiples
let (multiple, response) = key,
isMultiple: Bool = (n % multiple) == 0

if isMultiple
result += response


return result == "" ? String(n) : result

for i in 1...100
print(fizzBuzz(n: i))










share|improve this question











$endgroup$




















    2












    $begingroup$


    Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3 and 5).



    I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz return values.



    I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.



    How can I improve it?



    func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String 
    var result: String = ""

    for key in responsesByMultiples
    let (multiple, response) = key,
    isMultiple: Bool = (n % multiple) == 0

    if isMultiple
    result += response


    return result == "" ? String(n) : result

    for i in 1...100
    print(fizzBuzz(n: i))










    share|improve this question











    $endgroup$
















      2












      2








      2





      $begingroup$


      Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3 and 5).



      I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz return values.



      I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.



      How can I improve it?



      func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String 
      var result: String = ""

      for key in responsesByMultiples
      let (multiple, response) = key,
      isMultiple: Bool = (n % multiple) == 0

      if isMultiple
      result += response


      return result == "" ? String(n) : result

      for i in 1...100
      print(fizzBuzz(n: i))










      share|improve this question











      $endgroup$




      Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3 and 5).



      I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz return values.



      I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.



      How can I improve it?



      func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String 
      var result: String = ""

      for key in responsesByMultiples
      let (multiple, response) = key,
      isMultiple: Bool = (n % multiple) == 0

      if isMultiple
      result += response


      return result == "" ? String(n) : result

      for i in 1...100
      print(fizzBuzz(n: i))







      swift fizzbuzz






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 2 at 22:58







      Tiago Marinho

















      asked Aug 2 at 22:52









      Tiago MarinhoTiago Marinho

      2741 silver badge13 bronze badges




      2741 silver badge13 bronze badges























          1 Answer
          1






          active

          oldest

          votes


















          4












          $begingroup$

          🔆 Bright side



          Your code gives the correct output and delivers on the premise of extensibility.



          📝 Suggestions



          Here are some suggestions:



          1. The name key is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with responsesByMultiples. Then It would have made more sense for the latter to be named keys. Personally, I'd prefer to call responses or rules.


          2. These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.



          3. You can easily decompose a tuple this way:



            for (multiple, response) in responsesByMultiples 
            ...



          4. Calling the first element multiple is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that n is actually a multiple of multiple. It would make more sense to me to name the first element of the tuples dividsor.


          5. n is a bit too generic, use dividend instead.


          6. You don't have to specify the type in isMultiple: Bool, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.



          7. Instead of using (n % multiple) == 0, there is a nice syntax in Swift 5 :



            n.isMultiple(of: multiple)


            (this syntax exacerbates the problem mentioned in 4.)




          8. To check that a String is empty, it is more efficient to check the .isEmpty property. Here is a benchmark that confirms it:



            import Foundation

            let array = (0..<1_000_000).map _ in
            Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())


            do
            let start = Date()
            let result = array.filter $0 == ""
            let end = Date()

            print(result.count, end.timeIntervalSince(start))


            do
            let start = Date()
            let result = array.filter $0.isEmpty
            let end = Date()

            print(result.count, end.timeIntervalSince(start))



            The execution times are respectively 44ms and 34ms.



          💔 Putting it all together ❤️



          Here a version of your code that takes the previous points into account :



          func fizzBuzz (
          number dividend: Int,
          rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
          ) -> String

          var result: String = ""

          for (divider, response) in rules
          where dividend.isMultiple(of: divider)
          result += response


          return result.isEmpty ? String(dividend) : result



          🧐 Further reading



          You can find many implementations of this classic question on Code Review. Here is a quite informative one.






          share|improve this answer









          $endgroup$










          • 1




            $begingroup$
            Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
            $endgroup$
            – Tiago Marinho
            Aug 3 at 0:38













          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: "196"
          ;
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fcodereview.stackexchange.com%2fquestions%2f225438%2ffizzbuzz-with-more-parameters-in-swift%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









          4












          $begingroup$

          🔆 Bright side



          Your code gives the correct output and delivers on the premise of extensibility.



          📝 Suggestions



          Here are some suggestions:



          1. The name key is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with responsesByMultiples. Then It would have made more sense for the latter to be named keys. Personally, I'd prefer to call responses or rules.


          2. These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.



          3. You can easily decompose a tuple this way:



            for (multiple, response) in responsesByMultiples 
            ...



          4. Calling the first element multiple is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that n is actually a multiple of multiple. It would make more sense to me to name the first element of the tuples dividsor.


          5. n is a bit too generic, use dividend instead.


          6. You don't have to specify the type in isMultiple: Bool, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.



          7. Instead of using (n % multiple) == 0, there is a nice syntax in Swift 5 :



            n.isMultiple(of: multiple)


            (this syntax exacerbates the problem mentioned in 4.)




          8. To check that a String is empty, it is more efficient to check the .isEmpty property. Here is a benchmark that confirms it:



            import Foundation

            let array = (0..<1_000_000).map _ in
            Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())


            do
            let start = Date()
            let result = array.filter $0 == ""
            let end = Date()

            print(result.count, end.timeIntervalSince(start))


            do
            let start = Date()
            let result = array.filter $0.isEmpty
            let end = Date()

            print(result.count, end.timeIntervalSince(start))



            The execution times are respectively 44ms and 34ms.



          💔 Putting it all together ❤️



          Here a version of your code that takes the previous points into account :



          func fizzBuzz (
          number dividend: Int,
          rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
          ) -> String

          var result: String = ""

          for (divider, response) in rules
          where dividend.isMultiple(of: divider)
          result += response


          return result.isEmpty ? String(dividend) : result



          🧐 Further reading



          You can find many implementations of this classic question on Code Review. Here is a quite informative one.






          share|improve this answer









          $endgroup$










          • 1




            $begingroup$
            Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
            $endgroup$
            – Tiago Marinho
            Aug 3 at 0:38















          4












          $begingroup$

          🔆 Bright side



          Your code gives the correct output and delivers on the premise of extensibility.



          📝 Suggestions



          Here are some suggestions:



          1. The name key is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with responsesByMultiples. Then It would have made more sense for the latter to be named keys. Personally, I'd prefer to call responses or rules.


          2. These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.



          3. You can easily decompose a tuple this way:



            for (multiple, response) in responsesByMultiples 
            ...



          4. Calling the first element multiple is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that n is actually a multiple of multiple. It would make more sense to me to name the first element of the tuples dividsor.


          5. n is a bit too generic, use dividend instead.


          6. You don't have to specify the type in isMultiple: Bool, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.



          7. Instead of using (n % multiple) == 0, there is a nice syntax in Swift 5 :



            n.isMultiple(of: multiple)


            (this syntax exacerbates the problem mentioned in 4.)




          8. To check that a String is empty, it is more efficient to check the .isEmpty property. Here is a benchmark that confirms it:



            import Foundation

            let array = (0..<1_000_000).map _ in
            Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())


            do
            let start = Date()
            let result = array.filter $0 == ""
            let end = Date()

            print(result.count, end.timeIntervalSince(start))


            do
            let start = Date()
            let result = array.filter $0.isEmpty
            let end = Date()

            print(result.count, end.timeIntervalSince(start))



            The execution times are respectively 44ms and 34ms.



          💔 Putting it all together ❤️



          Here a version of your code that takes the previous points into account :



          func fizzBuzz (
          number dividend: Int,
          rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
          ) -> String

          var result: String = ""

          for (divider, response) in rules
          where dividend.isMultiple(of: divider)
          result += response


          return result.isEmpty ? String(dividend) : result



          🧐 Further reading



          You can find many implementations of this classic question on Code Review. Here is a quite informative one.






          share|improve this answer









          $endgroup$










          • 1




            $begingroup$
            Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
            $endgroup$
            – Tiago Marinho
            Aug 3 at 0:38













          4












          4








          4





          $begingroup$

          🔆 Bright side



          Your code gives the correct output and delivers on the premise of extensibility.



          📝 Suggestions



          Here are some suggestions:



          1. The name key is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with responsesByMultiples. Then It would have made more sense for the latter to be named keys. Personally, I'd prefer to call responses or rules.


          2. These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.



          3. You can easily decompose a tuple this way:



            for (multiple, response) in responsesByMultiples 
            ...



          4. Calling the first element multiple is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that n is actually a multiple of multiple. It would make more sense to me to name the first element of the tuples dividsor.


          5. n is a bit too generic, use dividend instead.


          6. You don't have to specify the type in isMultiple: Bool, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.



          7. Instead of using (n % multiple) == 0, there is a nice syntax in Swift 5 :



            n.isMultiple(of: multiple)


            (this syntax exacerbates the problem mentioned in 4.)




          8. To check that a String is empty, it is more efficient to check the .isEmpty property. Here is a benchmark that confirms it:



            import Foundation

            let array = (0..<1_000_000).map _ in
            Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())


            do
            let start = Date()
            let result = array.filter $0 == ""
            let end = Date()

            print(result.count, end.timeIntervalSince(start))


            do
            let start = Date()
            let result = array.filter $0.isEmpty
            let end = Date()

            print(result.count, end.timeIntervalSince(start))



            The execution times are respectively 44ms and 34ms.



          💔 Putting it all together ❤️



          Here a version of your code that takes the previous points into account :



          func fizzBuzz (
          number dividend: Int,
          rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
          ) -> String

          var result: String = ""

          for (divider, response) in rules
          where dividend.isMultiple(of: divider)
          result += response


          return result.isEmpty ? String(dividend) : result



          🧐 Further reading



          You can find many implementations of this classic question on Code Review. Here is a quite informative one.






          share|improve this answer









          $endgroup$



          🔆 Bright side



          Your code gives the correct output and delivers on the premise of extensibility.



          📝 Suggestions



          Here are some suggestions:



          1. The name key is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with responsesByMultiples. Then It would have made more sense for the latter to be named keys. Personally, I'd prefer to call responses or rules.


          2. These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.



          3. You can easily decompose a tuple this way:



            for (multiple, response) in responsesByMultiples 
            ...



          4. Calling the first element multiple is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that n is actually a multiple of multiple. It would make more sense to me to name the first element of the tuples dividsor.


          5. n is a bit too generic, use dividend instead.


          6. You don't have to specify the type in isMultiple: Bool, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.



          7. Instead of using (n % multiple) == 0, there is a nice syntax in Swift 5 :



            n.isMultiple(of: multiple)


            (this syntax exacerbates the problem mentioned in 4.)




          8. To check that a String is empty, it is more efficient to check the .isEmpty property. Here is a benchmark that confirms it:



            import Foundation

            let array = (0..<1_000_000).map _ in
            Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())


            do
            let start = Date()
            let result = array.filter $0 == ""
            let end = Date()

            print(result.count, end.timeIntervalSince(start))


            do
            let start = Date()
            let result = array.filter $0.isEmpty
            let end = Date()

            print(result.count, end.timeIntervalSince(start))



            The execution times are respectively 44ms and 34ms.



          💔 Putting it all together ❤️



          Here a version of your code that takes the previous points into account :



          func fizzBuzz (
          number dividend: Int,
          rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
          ) -> String

          var result: String = ""

          for (divider, response) in rules
          where dividend.isMultiple(of: divider)
          result += response


          return result.isEmpty ? String(dividend) : result



          🧐 Further reading



          You can find many implementations of this classic question on Code Review. Here is a quite informative one.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 3 at 0:23









          ielyamaniielyamani

          6281 gold badge4 silver badges15 bronze badges




          6281 gold badge4 silver badges15 bronze badges










          • 1




            $begingroup$
            Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
            $endgroup$
            – Tiago Marinho
            Aug 3 at 0:38












          • 1




            $begingroup$
            Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
            $endgroup$
            – Tiago Marinho
            Aug 3 at 0:38







          1




          1




          $begingroup$
          Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
          $endgroup$
          – Tiago Marinho
          Aug 3 at 0:38




          $begingroup$
          Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
          $endgroup$
          – Tiago Marinho
          Aug 3 at 0:38

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


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

          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f225438%2ffizzbuzz-with-more-parameters-in-swift%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

          Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form