Reputation: 119
Im trying to test if a number can be divided evenly by a group of numbers. This is my code:
var arr = [2, 3, 4, 5, 6, 7, 8, 9]
var text = Int(textField.text!)!
if text % arr === 0 {
}
What i'm trying to do is divide variable "text" by 2, 3, 4, 5, 6, 7, 8, and 9 (if it's divisible by any, perform the action) but i'm unsure how to get the value of the array. And I do not want to have to do:
if text % 2 == 0 || text % 3 == 0 || text % 4 == 0
etc...
Upvotes: 0
Views: 134
Reputation: 1789
A Swifty way to do this would be to use an if let
to unwrap the optionals and then use the built-in contains
function to see if the array contains an element that fulfills the predicate.
let arr = [2, 3, 4, 5, 6, 7, 8, 9]
if let text = textField.text, number = Int(text) {
if arr.contains({ number % $0 == 0 }) {
...
}
}
Upvotes: 3
Reputation: 2421
Have you tried this one?
for value in arr {
if text % value == 0 {
// do some action
break
}
}
Upvotes: 0
Reputation: 2627
for divider in arr {
if text % divider == 0 {
// ...
break
}
}
Upvotes: 2