100 days of swiftui: checkpoint 9
https://www.hackingwithswift.com/quick-start/beginners/checkpoint-9
Your challenge is this: write a function that accepts an optional array of integers, and returns one randomly. If the array is missing or empty, return a random number in the range 1 through 100.
If that sounds easy, it’s because I haven’t explained the catch yet: I want you to write your function in a single line of code. No, that doesn’t mean you should just write lots of code then remove all the line breaks – you should be able to write this whole thing in one line of code.
func getRandomInt(numbers: [Int]?) -> Int { numbers?.randomElement() ?? Int.random(in: 1..<101) }
print(getRandomInt(numbers: [0, -1, -2, -3, -4]))
print(getRandomInt(numbers: nil))
결과:
-1
46
랜덤 값이라서 실행할 때마다 값은 달라진다.
코드 파일
https://github.com/soaringwave/Ios-studying/commit/cee9a0529a140dda070f073b4d43334a02e80d27