5

I've just upgraded my project to Swift 3 from 2.3. All my for loops are going infinite. I can reproduce it in a fresh playground as well:

Here's what I'm doing:

var strs = [String!]()

strs.append("hello")
strs.append("world")

var count = 0
for s in strs {
    count += 1
}

What is wrong? In the playground, the loop executes continuously.

Looking at the docs from Apple, this should work, shouldn't it?

UPDATE: If I change my array definition as follows, it works as expected. What's the harm in forcing non-optional values in an array?

var strs = [String]()

UPDATE 2: This is a known bug - https://bugs.swift.org/browse/SR-1635

judepereira
  • 1,239
  • 2
  • 17
  • 24
  • 1
    Don't know for sure, but generally the way a `for` works is it creates an iterator that will eventually return `nil` when there are no more elements. Using `String!` as the element type may prevent that `nil` from ever being detected. – Kristopher Johnson Mar 13 '17 at 11:56
  • 1
    Duplicate of http://stackoverflow.com/q/38849549/2976878 – it's simply a bug. You shouldn't be able to have an array of IUOs, as they are no longer actual types (`var strs: [String!] = []` doesn't compile) – Hamish Mar 13 '17 at 11:57
  • A workaround may be to use `for i in 0.. – Kristopher Johnson Mar 13 '17 at 11:57
  • An array declared with an implicit unwrapped optional type is nonsense anyway. – vadian Mar 13 '17 at 11:59
  • Saw the bug report - I hope somebody fixes it. Thanks Hamish and Kristopher! – judepereira Mar 13 '17 at 12:01

0 Answers0