[英]Check if TWO objects are nil in Swift, ios xcode
我想比較兩個(相同類的)對象並返回非零值。
您如何迅速編寫這樣的內容? :
func returnWhatIsNotNil(objA: SomeClass, objB: SomeClass) -> SomeClass {
if objA != nil && objB != nil { //error
//both are not nil
return nil
}
if objA == nil && objB != nil { // error
// objA is nil
return objB
}
if objA != nil && objB == nil { // error
// objB is nil
return objA
}
}
一個物體
if let x = objA {
//objA is not nil
}
會完成這項工作,但是我安靜地不知道該如何使用兩個對象來完成這項工作。
編輯:對不起,您的原始問題有誤。 如果在兩個都不為nil
時都希望nil
,那么這里是一個單行代碼: return objA.map { objB == nil ? $0 : nil } ?? objB
return objA.map { objB == nil ? $0 : nil } ?? objB
return objA.map { objB == nil ? $0 : nil } ?? objB
。 但是,@ LeoDabus的版本使用if…let…where
對我而言更具可讀性。
進行預編輯,假設您都不想要任何一個時都想要第一個:
您要使用nil-coalescing運算符??
。 因此,要從函數中返回可選值,只需return objA ?? objB
return objA ?? objB
。 注意,所有輸入和輸出類型也必須是可選的。
通常情況下,如果沒有,則使用它來提供默認值,即"foo".toInt() ?? 0
"foo".toInt() ?? 0
,如果不為nil,則取消包裝該值;如果為nil,則將其替換為默認值。
但是,如果右側也是可選的,它將返回一個可選,左側的非零則為可選,否則將返回右側,即使那個為零。
let i: Int? = nil
let j: Int? = nil
let k: Int? = 42
if let num = i ?? j {
fatalError("won't execute")
}
if let num = j ?? k {
assert(num == 42, "k will be chosen")
}
else {
fatalError("this would run if all 3 were nil")
}
還請記住,您可以連鎖??
太:
let x = i ?? j ?? k ?? 0 // will result in an unwrapped 42
class SomeObject {
}
func returnWhatIsNotNil(objA: SomeObject?, objB: SomeObject?) -> SomeObject? {
if let objA = objA where objB == nil {
return objA
}
if let objB = objB where objA == nil {
return objB
}
return nil
}
作為@LeoDabus接受的答案的后續措施,您還可以使用switch
語句:
class SomeObject {
}
func returnWhatIsNotNil(objA: SomeObject?, objB: SomeObject?) -> SomeObject? {
switch (objA, objB) {
case (let a, nil): return a
case (nil, let b): return b
default: return nil
}
}
如前所述,零合並運算符??
可以使用。
這是函數的實現,請注意,您沒有定義當objA和objB均為非nil時會發生什么
func returnWhatIsNotNil(objA: SomeClass?, objB: SomeClass?) -> SomeClass? {
return objA ?? objB
}
雖然可以在Swift中對代碼進行文字轉換,但這是
func returnNotNil(num1: Int?, num2: Int?) -> Int?
{
if let x = num1 {
return x
}
else if let y = num2
{
return y
}
else
{
return nil
}
}
這里的問題是,在Swift中,我們必須將返回類型保持為可選-因此,一旦從函數返回,您將不得不再次檢查返回的值是否為nil並解包。 恕我直言,邏輯上的翻譯是(假設當它們都不為零時,您也不介意返回兩者)
func returnNotNilOrAssert(num1: Int?, num2: Int?) -> Int
{
if let x = num1 {
return x
}
else if let y = num2
{
return y
}
else
{
assert(false, "Both nil")
}
}
是否斷言,可能是您必須做出的實現選擇。 如果您完全確定,則另一種方法是使其中一個不為nil,使函數的返回類型“隱式展開”。 我知道您想在兩個都為nil時返回nil,但是隨后必須檢查此函數的返回值,該函數應該檢查兩個值並返回非nil的值,恕我直言,這沒有什么意義,因此我嘗試了這條路。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.