Reputation: 668
original code
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
let gestureRecognizers = NSMutableArray()
gestureRecognizers.addObject(tapGesture)
if let existingGestureRecognizers = sceneView.gestureRecognizers {
gestureRecognizers.addObjectsFromArray(existingGestureRecognizers)
}
sceneView.gestureRecognizers = gestureRecognizers
error -->> sceneView.gestureRecognizers = gestureRecognizers
unfortunately updated to latest version of swift 1.2
'NSMutableArray' is not convertible to '[AnyObject]'; did you mean to use 'as!' to force downcast?
it wants to change the line to
sceneView.gestureRecognizers = gestureRecognizers as! [AnyObject]
and after changing accepting, I now get this error
Cannot assign a value of type '[AnyObject]' to a value of type '[AnyObject]?'
the swift migrator was no help, neither are the release notes.
this is not my code as i didn't want to screw up my own repo so this a project from github.
https://github.com/ryanshelby/Stonehenge
thanks for any help
Upvotes: 0
Views: 554
Reputation: 27550
The Swift migrator is wrong in this case. Swift 1.2 does not support implicit casting from NSArray
to [AnyObject]
anymore so it correctly determined that a cast to [AnyObject]
was required but it incorrectly added it as an unsafe cast rather than a safe one. I'm assuming the unsafe cast is not valid code and should generate an error, but the message it's displaying is not correct.
The following line should give the desired result but matt is right that you probably want to rework your code to avoid NSMutableArray
:
sceneView.gestureRecognizers = gestureRecognizers as [AnyObject]
A concise way to avoid this would be to grab the original array or create a new one, insert the item, and reassign.
var gestureRecognizers = screenView.gestureRecognizers ?? []
gestureRecognizers.insert(tapGesture, atIndex: 0)
screenView.gestureRecognizers = gestureRecognizers
That said, UIView
already has an API for adding a single gesture recognizer:
screenView.addGestureRecognizer(tapGesture)
Upvotes: 5
Reputation: 535304
This doesn't directly answer your question, but your code was nutty to start with:
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
let gestureRecognizers = NSMutableArray()
gestureRecognizers.addObject(tapGesture)
if let existingGestureRecognizers = sceneView.gestureRecognizers {
gestureRecognizers.addObjectsFromArray(existingGestureRecognizers)
}
sceneView.gestureRecognizers = gestureRecognizers
What are you trying to do? If you want an array containing this gesture recognizer, just make it:
var gestureRecognizers =
[UITapGestureRecognizer(target: self, action: "handleTap:")]
If you then want to append the objects in the existing gesture recognizers, just append them:
gestureRecognizers.extend(existingGestureRecognizers)
By simplifying and rationalizing in this way, I think you'll solve your other difficulties.
Upvotes: 3