0

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

1
  • You can create enum block for this. Commented Jun 17, 2016 at 5:55

4 Answers 4

3

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 }) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is the best solution for the problem.
2
for divider in arr {
  if text % divider == 0 {
    // ... 
    break
  }
}

7 Comments

Haha :) at the same time :)
Looks like same answer like me :), So I'll delete my answer
There are a few issues with @Mr_Username's code that are not addressed in this answer. Additionally, looping over the array like that and using a break when the element is found is far from an idiomatic way to achieve this behavior in Swift. But it will work.
I would argue that you replace break with continue, that way you don't break the loop when fulfilling the condition.
Ok, then i don't see the need for a for-loop in the first place. Just use a .Contains() instead.. like @overactor suggested in his answer.
|
0
for i in arr {
  if text % i == 0
  {
  }
}

Comments

0

Have you tried this one?

for value in arr {
     if text % value == 0 {
          // do some action
          break
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.