Swift 类型转换
xxxixxxx

Swift 类型转换 as 的使用

if let as

类型转换,此时 btnAny 类型,使用 as? 将他尝试转为 UIButton类型。并赋值给 a。 实际开发中建议 abtn 命名一致,这里为了便于区分

1
2
3
4
5

if let a = btn as? UIButton {
print(a)
// 这里 a 为真
}

guard let as

if let as 基本一致,只是当转换失败时提前退出。适用于一些异步回调里。

1
guard let btn = btn as? UIButton else { return }
  • Post title:Swift 类型转换
  • Post author:xxxixxxx
  • Create time:2020-12-21 16:57:00
  • Post link:https://xxxixxx.github.io/2020/12/21/100-Swift-类型转换/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments