【发布时间】:2019-09-04 11:30:56
【问题描述】:
我希望能够有多个 let 并且下一个 let 能够使用前一个变量 only 如果它不为空。我想要这个的原因是因为我只想要一个:?对于所有的让。这可能吗?
我想要的示例:
fun example() {
firstVariable?.let a -> &&
exampleFunction(a, 3)?.let { a, b ->
// Use a and b freely since they are not null and not optionals
} ?: run {
// Runs if either one of the let is failing
}
}
// a is NOT optional
fun exampleFunction(a: Int, b: Int?): Int? {
if (b == null) {
return null
}
return a + b
}
愚蠢的例子,但它只是为了展示我需要什么......我想检查第一个变量是否为空并运行一个函数,该函数返回一个带有非可选参数的可选函数,该参数是第一个变量 - 如果有的话其中一个失败,我想运行其他东西。
我知道如何在不让的情况下做到这一点,但我想知道是否有可能或计划能够做到这一点? (在 Swift 中是可能的)。
如何在 Swift 中做到这一点:
// First check a, then use a in the same expression if its validated
if let a = firstVariable,
let b = exampleFunction(a) {
// Use a and b as non-optionals
} else {
// a or b failed
}
【问题讨论】:
-
我相信目前还没有这样的功能,但如果你满意,你可以随时创建自己的扩展功能
-
我不确定如何编写这样的函数。你能举个例子吗? :)
-
@Eugene 该链接不能解决我的问题,因为下一个让不能使用第一个结果(正如我在那里评论的那样)。如前所述:示例函数很愚蠢,但只是为了证明我的观点。
-
不能解决我的问题。只有当第一个变量不为空时,我才想使用第一个变量的结果。
-
@Eugene 更新了问题,让我更清楚我想做什么。