您如何解开Swift可选项? [英] How do you unwrap Swift optionals?
问题描述
您如何正确地包装普通和隐式可选件?
How do you properly unwrap both normal and implicit optionals?
这个主题似乎有些混乱,我只想对所有方法以及它们如何有用提供参考.
There seems to be confusion in this topic and I would just like to have a reference for all of the ways and how they are useful.
当前有两种创建可选内容的方法:
There are currently two ways to create optionals:
var optionalString: String?
var implicitOptionalString: String!
有两种方法都可以解开包装吗?另外,在展开过程中使用!
和?
有什么区别?
What are all the ways to unwrap both? Also, what is the difference between using !
and ?
during the unwrapping?
推荐答案
有很多相似之处,但有一些区别.
There are many similarities and just a handful of differences.
-
声明:
var opt: Type?
不安全地展开:let x = opt!.property // error if opt is nil
安全地测试存在性:if opt != nil { ... someFunc(opt!) ... } // no error
通过绑定安全地展开:if let x = opt { ... someFunc(x) ... } // no error
Safely unwrapping via binding: if let x = opt { ... someFunc(x) ... } // no error
安全链接:var x = opt?.property // x is also Optional, by extension
安全合并nil值:var x = opt ?? nonOpt
-
声明:
var opt: Type!
不安全地展开(隐式):let x = opt.property // error if opt is nil
Unsafely unwrapping (implicit): let x = opt.property // error if opt is nil
-
通过分配不安全地展开:
let nonOpt: Type = opt // error if opt is nil
Unsafely unwrapping via assignment:
let nonOpt: Type = opt // error if opt is nil
通过参数传递不安全地展开:
func someFunc(nonOpt: Type) ...
someFunc(opt) // error if opt is nil
Unsafely unwrapping via parameter passing:
func someFunc(nonOpt: Type) ...
someFunc(opt) // error if opt is nil
安全测试存在:if opt != nil { ... someFunc(opt) ... } // no error
安全链接:var x = opt?.property // x is also Optional, by extension
安全合并nil值:var x = opt ?? nonOpt
这篇关于您如何解开Swift可选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!