JWSTelescope
JWSTelescope

Reputation: 3

Swift - trying to loop through stringValue from text field

I'm trying to iterate over every character from a text field,

here's how I did it:

@IBOutlet var needTranslate : NSTextField
for i in needTranslate.stringValue{

then I get an error: SourceKitService terminated

and it happens only when I try to loop through this string value. I understand that's a bug but am I doing something wrong in the code?

Upvotes: 0

Views: 784

Answers (1)

Martin R
Martin R

Reputation: 539925

That looks like a compiler bug to me.

  • Your code causes a runtime exception of the swift compiler itself. This should not happen even for completely wrong source code.
  • Your code looks in fact correct (to me) because the return value of stringValue is an implicitly unwrapped optional string.

The problem can be reproduced with

var s : String! = "foo"
for i in s {
    println(i)
}

I cannot see from the documentation why a for ... in ... loop should not work with an implicitly unwrapped string, so I would recommend to file a bug report at Apple.

As a workaround, you can treat the return value of stringValue like a "normal" optional and unwrap it explicitly with an optional binding:

if let str = needTranslate.stringValue {
    for i in str {
         println(i)  
    }
}

Upvotes: 1

Related Questions