20

I've updated my code to XCode 7 and Swift 2.0, now some of my tests fail and I see a list of 40 warnings in the Test build that are completely unrelated with the code they refer to. The warning message is:

"Cast From 'XCUIElement' to unrelated type 'String' always fails" 

And this is an example of a row that produces the warning:

if let protocolStr = JSON["version"] as? String{

I'm not using XC user interface tests yet... so I cannot understand why this code is referring to that class. Any idea?

Update: November 9 With XCode 7.1 the issue is still there.

MatterGoal
  • 16,038
  • 19
  • 109
  • 186

4 Answers4

10

With Xcode 7.1.1 Not fixed but this workaround helped me:

if let protocolStr = JSON["version"] as AnyObject as! String {
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
Eis
  • 191
  • 7
  • We ran into the same issue (Xcode 7.2), and your workaround _actually works_ for us too! But I can't reason why. What was your reasoning for casting this way? – epologee Dec 16 '15 at 12:33
  • 1
    I suspect it has something to do with the UI Testing module because this only appears to be a problem when writing unit tests. My guess is there is an extension on `AnyObject` somewhere to add subscripting that returns an XCUIElement as a convenience for writing UI tests. Something like https://developer.apple.com/reference/xctest/xcuielementquery/1500776-subscript that leaks into AnyObject ... – Sebastien Martin Jul 13 '16 at 12:52
2

I think you already fixed your issue, but in case anyone else is looking at this:

The problem is that JSON is of type AnyObject I'm guessing, at it doesn't know that you can index it as a dictionary. If you cast it as [String : AnyObject] before hand it won't give you an error. (like you noticed)

edit: As for why it's giving you that error specifically, I'm not sure. Probably a bug.

ssrobbi
  • 496
  • 1
  • 5
  • 15
  • 1
    This cast doesn't work only with the test target. The application target accepts this cast without any problem. – MatterGoal Oct 01 '15 at 06:16
  • Nope it didn't work. The issue is still there, and we DON'T have to find a workaround, Apple HAS TO fix this bug. – MatterGoal Nov 09 '15 at 10:52
  • Hmm, perhaps it was situational for me. And MatterGoal I agree with you, but Apple generally doesn't give a flying f**** what you think they have to do. I've had bugs reported for well over a year they haven't even acknowledged. – ssrobbi Dec 15 '15 at 21:07
1

All I had to do was type the key string (“version”) to NSString like so:

if let protocolStr = JSON["version" as NSString] as? String {
    …
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
SushiGrass Jacob
  • 19,425
  • 1
  • 25
  • 39
1

Xcode 7.2, swift 2.2

Try like this

if let protocolStr = JSON.valueForKey("version") as? String{
     //your code
}
Alupotha
  • 9,710
  • 4
  • 47
  • 48