swift可选链
2021-12-25 本文已影响0人
一个好笑的人
private func displayOne(_ annotationType: AnyClass) {
let annotation = allAnnotations?.first { (annotation) -> Bool in
return annotation.isKind(of: annotationType)
}
if let oneAnnotation = annotation {
displayedAnnotations = [oneAnnotation]
} else {
displayedAnnotations = []
}
}
去掉?报错为:
Value of optional type '[MKAnnotation]?' must be unwrapped to refer to member 'first' of wrapped base type '[MKAnnotation]'
提示解决方案:
Chain the optional using '?' to access member 'first' only for non-'nil' base values
Force-unwrap using '!' to abort execution if the optional value contains 'nil'
结论:
想让解包为空的时候优雅结束用“?” 想让为空时直接终止程序用“!”