1

I wrote the following code in swift(2.2):

for var i = 2; sqrt(Double(num)) >= Double(i); i += 1 {.....}

However, I keep getting a warning message which reads "c-style for statement is deprecated and will be removed in future version of swift".

So, what is the proper way of writing the same loop is "Swift style"? Casting the value of num as double gives me error with "Swift style". Any suggestions?

Thank you.

Saman Ray
  • 115
  • 2
  • 11

2 Answers2

2

You can refactor your deprecated C-style for loop using the for-in construct

for i in 2...Int(sqrt(Double(num))) { }

However if you really want to go essential try defining this operator to find the square root of an int rounded down to the closest int.

prefix operator √ {}
prefix func √ (number: Int) -> Int {
     return Int(sqrt(Double(number)))
}

Now you can write your for loop this way

for i in 2...(√num) { }
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
1

The For loop in Swift 2.2 is re-designed for use in iterating over a sequence, such as ranges of numbers, items in an array, or characters in a string. The condition in your For loop is not easily converted into sequence or range, so it would be best to re-write it as a While loop.

bbabin
  • 21
  • 6