簡體   English   中英

在Swift中使用可選值

[英]Use of an optional value in Swift

在閱讀The Swift Programming Language時 ,我遇到了這個片段:

您可以使用iflet一起使用可能缺少的值。 這些值表示為選項 可選值包含值或包含nil以指示缺少值。 在值的類型后面寫一個問號(?)以將值標記為可選。

// Snippet #1
var optionalString: String? = "Hello"
optionalString == nil

// Snippet #2     
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

Snippet#1足夠清晰,但是在Snippet#2中發生了什么? 有人可以分解並解釋嗎? 它只是使用if - else塊的替代方法嗎? 在這種情況下, let的確切作用是什么?

我確實看過這個頁面,但還是有點困惑。

if let name = optionalName {
   greeting = "Hello, \(name)"
}

這有兩件事:

  1. 它檢查optionalName是否有值

  2. 如果是,它將“解包”該值並將其分配給名為name的String(僅在條件塊內部可用)。

請注意, name的類型是String (不是String? )。

如果沒有let (即只if optionalName ),它只有在有值的情況下才會進入塊,但是您必須手動/顯式訪問String作為optionalName!

// this line declares the variable optionalName which as a String optional which can contain either nil or a string. 
//We have it store a string here
var optionalName: String? = "John Appleseed"

//this sets a variable greeting to hello. It is implicity a String. It is not an optional so it can never be nil
var greeting = "Hello!"

//now lets split this into two lines to make it easier. the first just copies optionalName into name. name is now a String optional as well.
let name = optionalName

//now this line checks if name is nil or has a value. if it has a value it executes the if block. 
//You can only do this check on optionals. If you try using greeting in an if condition you will get an error
if  name{
    greeting = "Hello, \(name)"
}

String? 是一個盒裝類型,變量optionalName要么包含String值,要么包含任何值(即nil )。

if let name = optionalName是一個習慣用法,它會將該值從optionalName取消裝箱並將其分配給name 同時,如果名稱為非nil,則執行if分支,否則執行else分支。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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