Mr_Username
Mr_Username

Reputation: 119

How to change [int] to int in Swift

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

Answers (4)

overactor
overactor

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

Oleg Novosad
Oleg Novosad

Reputation: 2421

Have you tried this one?

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

Upvotes: 0

Jayesh Miruliya
Jayesh Miruliya

Reputation: 3317

for i in arr {
  if text % i == 0
  {
  }
}

Upvotes: 0

Viktor Simkó
Viktor Simkó

Reputation: 2627

for divider in arr {
  if text % divider == 0 {
    // ... 
    break
  }
}

Upvotes: 2

Related Questions