[英]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 ? 我正在将NSArray投射到NSIndexPath,以便可以在reloadRowsAtIndexPath中使用它,有人可以提出更好的解决方案,为什么我会收到警告“从NSArray广播到无关类型的NSIndexPath总是失败”,我是否需要为此担心?
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. 该警告告诉您正在将
NSArray
强制转换为NSIndexPath
,并且您不能这样做。 In other words, indexArray
will always be nil
. 换句话说,
indexArray
将始终为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. 遇到麻烦的原因是,您根本不需要
reloadRowsAtIndexPaths()
为NSIndexPath
: reloadRowsAtIndexPaths()
期望使用索引路径数组,尽管您可以更轻松地完成此操作,但这正是您所创建的。 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. [indexPath]
意思是“一个包含indexPath
的数组”,因此可以轻松地创建reloadRowsAtIndexPaths()
寻找的数组。 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 !
请注意,您应该尽可能使用
if let
和其他安全的解包方法-Swift的初学者应该假装该!
means "please crash now". 表示“请立即崩溃”。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.