0x00 Lesson

Optional strings might contain a string like “Hello” or they might be nilnothing at all.

Consider this optional string:

vaf name: String? = nil

What happens if we use name.count? A real string has a count property that stores how many letters it has, but this is nil – it’s empty memory, not a string, so it doesn’t have a count.

Because of this, trying to read name.count is unsafe and Swift won’t allow it. Instead, we must look inside the optional and see what’s there – a process known as unwrapping.

A common way of unwrapping optionals is with if let syntax, which unwraps with a condition. If there was a value inside the optional then you can use it, but if there wasn’t the condition fails.

For example:

if let unwrapped = name {
	print("(unwrapped.count) letters")
} else {
	print("Missing name.")
}

if name holds a string, it will be put inside unwrapped as a regular String and we can read its count property inside the condition. Alternatively, if name is empty, the else code will be run.


0x01 我的小作品

欢迎体验我的作品之一:小五笔
五笔学习好帮手
App Store 搜索即可~


原文地址:https://blog.csdn.net/xjh093/article/details/128897323

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_26276.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注