gpt4 book ai didi

swift 相当于 "?:"

转载 作者:行者123 更新时间:2023-11-28 09:45:47 29 4
gpt4 key购买 nike

ObjC

[MyObject doThisWithString:string?: [MyObject otherString]];

我如何在 Swift 中执行此操作?

extension MyObject {
func doThisWithString(string: String?) {
... <- assume defined
}

func otherString() -> String {
return ... <- assume defined
}
}

var MyInstance: MyObject
...
MyInstance.doThisWithString(myStringVar?: MyInstance.otherString()) <- how do I do this?

最佳答案

有一个'??'称为“Nil 合并”运算符的运算符。它做的正是你需要的。引用documentation :

Nil Coalescing Operator

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil coalescing operator is shorthand for the code below:

a != nil ? a! : b

在您的情况下,您可以将表达式写为:

MyInstance.doThisWithString(myStringVar ?? MyInstance.otherString()) 

关于 swift 相当于 "?:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470311/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com