也许有或没有一种简单的方法可以编写此代码,但是我觉得自己是Swift的新手,我可能会缺少一些东西。我有一个方法的参数(文件名),该方法是可选的,String?
我需要检查它是否为nil
,或者是否为空字符串。这是我所拥有的代码,并且工作正常,但似乎可能更简洁/可读性更高。
func writeFile(fileName: String?, withContents contents: String, errorCallback failureCallback: RCTResponseSenderBlock, callback successCallback: RCTResponseSenderBlock) -> Void {
// If fileName has a value -- is not nil
if let fileName = fileName {
// Check to see if the string isn't empty
if count(fileName) < 1 {
// Craft a failure message
let resultsDict = [
"success": false,
"errMsg": "Filename is empty"
]
// Execute the JavaScript failure callback handler
failureCallback([resultsDict])
return; // Halt execution of this function
}
// else, fileName is nil, and should return the same error message.
} else {
// Craft a failure message
let resultsDict = [
"success": false,
"errMsg": "Filename is empty"
]
// Execute the JavaScript failure callback handler
failureCallback([resultsDict])
return; // Halt execution of this function
}
}
怎么样
首先创建一个可选的nil字符串,以设置示例var fileName:字符串?
现在,使您可以在简单的一行中查看文件名是否为nil / empty的代码:
if (fileName ?? "").isEmpty
{
println("empty")
}
else
{
println("not empty")
}
这使用??
了Swift的“零合并运算符”。(关联)
对于表达式:
a ?? b
它在哪里a
是可选的:
如果a不为nil,则返回a。如果a为零,则返回b。
所以
if (fileName ?? "").isEmpty
说
首先,评估fileName并查看它是否为nil。如果是这样,请将其替换为空字符串。
接下来,检查结果以查看是否为空。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句