Is it possible to do a for loop while Int is in a specific range in swift?

Is it possible to do a regular loop while Int is in a specific range in swift?

this is what i want to achieve:

func someFunc(var plusOrMinus:Int) {

    for var i:Int = 0; i == -8...8;i += plusOrMinus {

 }
}

      

or

func someFunc(var plusOrMinus:Int) {

    for var i:Int = 0; i in -8...8;i += plusOrMinus {

 }
}

      

or

func someFunc(var plusOrMinus:Int) {

    for var i:Int = 0; i == <-8,8>;i += plusOrMinus {

 }
}

      

None of these works. I hope you can understand the question and can help me. :)

+3


source to share


2 answers


To check if Int

in a range -8...8

, you can simply check both ends of the range with a conditional and concatenate them with &&

:

func someFunc(var plusOrMinus:Int) {

    for var i = 0; i >= -8 && i <= 8; i += plusOrMinus {
        println(i) 
    }
}

      

Note: Swift can infer the type Int

, so you don't need to assign it explicitly.



From @ MartinR's comment, you can use the pattern matching operator ~=

to check if it is i

in this range, but the above method is simpler and probably more efficient.

func someFunc(var plusOrMinus:Int) {

    for var i = 0; -8...8 ~= i; i += plusOrMinus {
        println(i)
    }
}

      

+2


source


If you want to use for ... instead of a C-style loop, you can use stride

, but check in which direction you are going to determine if you want the target to be less than or greater than the initial value:

func someFunc(plusOrMinus: Int) {
    precondition(plusOrMinus != 0)
    let target = plusOrMinus > 0 ? 8 : -8

    for i in stride(from: 0, through: target, by: plusOrMinus) {
        println(i)
    }
}

      



The range -8...8

you were looking for is possible, but you must explicitly create a closed interval and then check that your counter is inside it:

func someFunc(plusOrMinus: Int) {
    let interval = -8...8 as ClosedInterval
    for var i = 0; interval.contains(i); i += plusOrMinus {
        println(i)
    }
}

      

+1


source







All Articles