簡體   English   中英

如何將可選轉換為非可選然后調用它?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM