在这本书的一些章节中,有这样的线条:

if let error = error as NSError?

在SWIFT中,我通常会看到这样的可选绑定:

if let something = something as? Type

有人可以解释差异,为什么我们使用“作为类型?”而不是“如同?类型“,我不明白。

谢谢!

1 Like

@ritsz. The first line of code uses as to typecast error to NSError? because you are sure that error is of type NSError? in this case.

The second line of code uses as? to downcast something to Type since this definitely fails if something isn’t of type Type.

如果您有机会,请告诉我您是否有任何关于整件事的问题或问题。谢谢!

To me it looks weird to use if let when typecasting to an optional, I’m used to see it for optional binding (to unwrap the optional) instead, but I understand. Thank you.

@ritsz. You use if let in the first case to unwrap error because it may be nil since it is of type NSError?.

You use if let in the second case to unwrap something because it is nil if the downcast to Type fails.

如果您有机会,请告诉我您是否有任何关于整件事的问题或问题。谢谢!

这一主题在166天后自动关闭。不再允许新的回复。