0

I have tried all imagined ways and searched for it in Google, StackOverflow and official reference book, but still couldn't find out how to do such operation in Swift:

let basicPrimes = (1,2,3,5,7,11,13,17,19)
if number in basicPrimes {
    println("Is prime!")
}

Error message says "Braced block of statements is an unused closure" but I couldn't find any plausible explanation on it that I could make use of.

Any idea what am I doing wrong?

Marinho Brandão
  • 637
  • 1
  • 9
  • 30
  • 1
    pedantic: [1 isn't prime](http://math.stackexchange.com/q/120/49763). –  Dec 30 '14 at 22:40
  • 1
    Do you need to work with Tuples? Why not make an array? Then you could use `contains()` – Ben Kane Dec 30 '14 at 22:45
  • Related: [How to check if an element is in an array](http://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array). – Martin R Dec 30 '14 at 22:50

2 Answers2

3

I'd suggest using an Array instead of a Tuple for your basic primes. Then you could use contains() to check if a number is in your array of basic primes. Something like this would work:

let basicPrimes = [2, 3, 5, 7, 11, 13, 17, 19]
let number = 5

if contains(basicPrimes, number)
{
    println("Is prime!")
}
Ben Kane
  • 9,331
  • 6
  • 36
  • 58
1

There are 2 errors in your code:

  1. an array is initialized with square brackets - what you have created instead is a tuple, which is not a sequence type

  2. to check if an element is contained in a sequence, you have to use the contains global function - in is a keywords used in closures instead, that's the reason for that strange error message

So your code should look like:

let basicPrimes = [1,2,3,5,7,11,13,17,19]
if contains(basicPrimes, number) {
    println("Is prime!")
}
Antonio
  • 71,651
  • 11
  • 148
  • 165