简体   繁体   中英

Swift : Cast from NSArray to unrelated type NSIndexPath Always fails

I am casting an NSArray to NSIndexPath so that i can use that in my reloadRowsAtIndexPath, can anyone suggest better solution and why do i get the warning "Cast from NSArray to unrelated type NSIndexPath Always fails" and do i have to be worried about this ?

code

let indexArray : NSIndexPath? = NSArray(Objects:NSIndexPAth(forRow: 0, inSection:2)) as? NSIndexPath
self.myTableView.reloadRowsAtIndexPaths(indexArray!], withRowAnimation:UITableViewRowAnimation.None)

You definitely do have to be worried about that, especially because you force unwrap it (with ! ) on the very next line. That warning is telling you that you're casting an NSArray to an NSIndexPath , and that you can't do that. In other words, indexArray will always be nil . And because you force unwrap it on the next line, it will always crash.

The reason you're having trouble is because you don't need to cast to NSIndexPath at all: reloadRowsAtIndexPaths() expects an array of index paths, which is what you made, although you could make it much more easily. Here's the simple way to rewrite your code:

let indexPath = NSIndexPath(forRow: 0, inSection:2)
self.myTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)

[indexPath] means "an array containing indexPath ", so that creates the array that reloadRowsAtIndexPaths() is looking for quite easily. As you can see, no casting is required.

Note that you should use if let and other safe unwrapping methods as much as possible--beginners to Swift should pretend that ! means "please crash now". :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM