[英]How to convert an optional to a non-optional and then call it?
class FeedCell: UICollectionViewCell {
var viewModel: PostViewModel? {
didSet { configure() }
}
weak var delegate: FeedCellDelegate?
//如果 post 是可选的,我会在 var videoURL 处收到错误消息“可选类型的值 'Post?' 必须解包以引用已包装的基本类型'Post'的成员'videoURL'。” 如果我将 var post 更改为非可选以调用 post.videoURL,那么我会在 super.init 中收到一个错误,提示“Property 'self.post' not initialized at super.init call”
var post: Post?
var videoUrl: URL { post.videoURL }
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .black
ddSubview(postImageView)
postImageView.anchor(top: profileImageView.bottomAnchor, left: leftAnchor, right: rightAnchor,
paddingTop: 10)
postImageView.heightAnchor.constraint(equalTo: widthAnchor, multiplier: 1).isActive = true
}
有多种方法可以将可选项转换为非可选项。 您可以在Swift Programming Language Guide中阅读很多关于它们的信息。 第一种方法是可选绑定:
let optionalInt: Int? = 5
print(type(of: optionalInt)) // Prints Optional<Int> - At this moment, the content of the optionalInt variable MIGHT be nil
if let unwrappedInt = optionalInt { // If optionalInt is NOT nil, this statement will be true and I enter the if-block
print(unwrappedInt) // Prints 5 - Now I know for sure that unwrappedInt is not nil
print(type(of: unwrappedInt)) // Prints Int - Not optional anymore
}
您也可以使用guard
语句来完成相同的操作,而无需嵌套:
let optionalInt: Int? = 5
print(type(of: optionalInt)) // Prints Optional<Int> - At this moment, the content of the optionalInt variable MIGHT be nil
guard let unwrappedInt = optionalInt else { return }
print(unwrappedInt) // Prints 5 - Now I know for sure that unwrappedInt is not nil (otherwise it retuns)
print(type(of: unwrappedInt)) // Prints Int - Not optional anymore
另一种方法是可选链接。 您可以使用强制展开(即optionalInt!
),但除非您确定该值不是nil
并且不会是nil
,否则您不应该这样做。 强制解包被认为是不好的做法,因为这可能会导致强制解包nil
值(这会导致您的应用程序崩溃)。
编辑:
在您的情况下, post
是可选的。 在其他地方使用它作为非可选,您可以使用可选链接。 例如: var videoUrl: URL { post?.videoURL }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.