Joseph Beuys' Mum
Joseph Beuys' Mum

Reputation: 2274

Swift - Type 'int' does not conform to protocol 'intervaltype'

I found the following tutorial, which suggests the code after it should work. However, both cases throw type 'int' does not conform to protocol 'intervaltype' errors

Swift switch tutorial: http://www.codingexplorer.com/loops-switch-statements-ranges-swift/

let arrayCount = someArray?.count

switch arrayCount
{
case 0:
    println("zero")
case 1:
    println("one")
default:
    println("etc")
}

Upvotes: 0

Views: 810

Answers (3)

Aleksi Sjöberg
Aleksi Sjöberg

Reputation: 1474

The problem is that arrayCount is of type Int?, so you should either implicitly unwrap it when you use switch on it:

switch arrayCount! { }

which is bad in case arrayCount is nil. Another option is that you could make sure arrayCount has a value by using coalescing operator, like this:

let arrayCount: Int = someArray?.count ?? 0

which would work in your code the way you tried to use it and also make sense for arrayCount to be 0.

Upvotes: 0

sbooth
sbooth

Reputation: 16976

The array is declared as an optional so its count is of type Optional(Int). It's necessary to check whether someArray is nil before using the count in a switch statement. Here is one way:

if let arrayCount = someArray?.count {
    switch arrayCount {
        case 0:
            println("zero")
        case 1:
            println("one")
        default:
            println("etc")
    }
}

If the array isn't nil the assignment will succeed and the if block will execute.

If you're certain the array isn't nil you can unwrap the optional using let arrayCount = someArray!.count instead of the conditional assignment.

Upvotes: 2

chrissukhram
chrissukhram

Reputation: 2967

Try this:

let arrayCount:Int = someArray?.count as Int

switch arrayCount
{
   case 0:
   println("zero")
case 1:
    println("one")
 default:
    println("etc")
}

Upvotes: 0

Related Questions