且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将我的代码转换成更好的Swift类似答案,以获取FizzBu​​zz响应

更新时间:2023-10-02 22:51:52

在操场上尝试一下.这是一种尝试实用的方法.效率不高.

let range = (1...100)
let fizz  = range.map{ ($0 % 3 == 0) ? "Fizz" : "" }
let buzz  = range.map{ ($0 % 5 == 0) ? "Buzz" : "" }
zip(range, zip(fizz, buzz))
  .map {
    let fb = $1.0 + $1.1
    print(fb.isEmpty ? $0 : fb)
  }

I was searching the internet last night while working on some programming, and I noticed that there was this interesting test that employers sometimes use for testing programmers to see if they can actually apply code to a real world problem. It is referred to as the FizzBuzz test, and it works like this.

"Write a program that prints the numbers 1 to 100. But, for multiples of 3, print "Fizz" instead of the number and for multiples of 5, print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"."

Now, I sat down and came up with this code very quickly, which I placed in my viewDidLoad method:

for i in 1...100 {
            if i % 3 = 0 && i % 5 == 0 {
                print("FizzBuzz")
            } else if i % 3 == 0 {
                print("Fizz")
            } else if i % 5 == 0 {
                print("Buzz")
            } else {
                print(i)
            }
        }

And, although this fulfils the brief, I feel very dissatisfied by using this as my solution (it seems too simple and basic to me).

I have recently read the book, iOS 9 Programming Fundamentals With Swift by Matt Neuburg (this book has blown my mind and opened my eyes in so many levels). And I am captivated by trying to make things as Swift-y as possible (passing functions, and the like). Then, I came to the sobering and disheartening realisation that I really have no idea how to improve this code.

Therefore, I am turning to the Swift community in hopes that you could better educate me on what would be the most sophisticated Swift answer for the FiizBuzz test question.

I am desperately trying to improve my Swift programming and would like to know a better Swift-y programming approach to my code.

Try this in a playground. It is an attempt at a functional approach. It is not efficient.

let range = (1...100)
let fizz  = range.map{ ($0 % 3 == 0) ? "Fizz" : "" }
let buzz  = range.map{ ($0 % 5 == 0) ? "Buzz" : "" }
zip(range, zip(fizz, buzz))
  .map {
    let fb = $1.0 + $1.1
    print(fb.isEmpty ? $0 : fb)
  }