简体   繁体   中英

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?

//If post is an optional I get an error at var videoURL saying "Value of optional type 'Post?' must be unwrapped to refer to member 'videoURL' of wrapped base type 'Post'." If I change var post to a non optional in order to call post.videoURL then I get an error in super.init saying "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
        
        
}

There are multiple ways to convert an optional to a non-optional. You can read a lot about them in the Swift Programming Language Guide . The first method is optional binding:

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
}

You could also use a guard statement to accomplish the same, without nesting:

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

Another method is optional chaining . You could use force unwrapping (ie optionalInt! ), but you shouldn't unless you know for certain that the value isn't nil , and isn't going to be nil . Force unwrapping is considered bad practice as this might lead to force unwrapping a nil value (which causes your app to crash).

EDIT:

In your case, post is optional. The use it somewhere else as a non-optional, you could use optional chaining. For example: var videoUrl: URL { post?.videoURL }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM