Swift3 在Swift 3中,“thing=this()| that”与“thing=this()| that”是什么意思?

Swift3 在Swift 3中,“thing=this()| that”与“thing=this()| that”是什么意思?,swift3,Swift3,在大多数语言中,我都可以这样写: this = this() || that() let result = this() ?? that() 如果this()返回假值,如整数0,this()将被计算。很普通的成语 Swift 3不会自动将Int强制转换为Bool,所以成语不起作用。在Swift 3中,什么是简洁的方法?在Swift中没有完全相同的方法,例如: 除了Bool之外,没有其他类型不能转换为Bool 不能编写返回Bool或Int (在大多数语言中有点夸张,不能用Java、C#或许

在大多数语言中,我都可以这样写:

this = this() || that()
let result = this() ?? that()
如果
this()
返回假值,如整数0,
this()
将被计算。很普通的成语


Swift 3不会自动将
Int
强制转换为
Bool
,所以成语不起作用。在Swift 3中,什么是简洁的方法?

在Swift中没有完全相同的方法,例如:

  • 除了
    Bool
    之外,没有其他类型不能转换为
    Bool

  • 不能编写返回
    Bool
    Int

(在大多数语言中有点夸张,不能用Java、C#或许多其他强类型语言编写这样的东西。)

Swift中最相似的东西是--
??

假设
this()
返回
Int?
(又名
可选
),而
that()
返回
Int
(非可选):

并使用如下所示的零合并运算符:

this = this() || that()
let result = this() ?? that()

在该赋值中,如果
this()
返回非零值,则不计算
that()
,并将该非零值赋值给
result
。当
this()
返回
nil
时,将计算
that()
,并将值分配给
result

,Swift中没有确切的等价项,如下所示:

  • 除了
    Bool
    之外,没有其他类型不能转换为
    Bool

  • 不能编写返回
    Bool
    Int

(在大多数语言中有点夸张,不能用Java、C#或许多其他强类型语言编写这样的东西。)

Swift中最相似的东西是--
??

假设
this()
返回
Int?
(又名
可选
),而
that()
返回
Int
(非可选):

并使用如下所示的零合并运算符:

this = this() || that()
let result = this() ?? that()

在该赋值中,如果
this()
返回非零值,则不计算
that()
,并将该非零值赋值给
result
。当
this()
返回
nil
时,将计算
that()
,并将值分配给
result

nil
合并运算符是此处的“适合用途”习惯用法,但作为旁注,您可以通过重载
|
操作符来实现所描述的功能,例如,对于符合某些类型约束的类型。例如,使用
整数
作为类型约束:

extension Bool {
    init<T : Integer>(_ value: T) {
        self.init(value != 0)
    }
}

func ||<T: Integer>(lhs: T, rhs: @autoclosure () -> T) -> T {
    return Bool(lhs) ? lhs : rhs()
}

var thisNum = 0
let thatNum = 12
thisNum = thisNum || thatNum
print(thisNum) // 12
扩展Bool{
初始值(u值:T){
self.init(值!=0)
}
}
func | |(左:T,右:autoclosure()->T)->T{
返回布尔(lhs)?lhs:rhs()
}
var thisNum=0
让thatNum=12
thisNum=thisNum | | thatNum
打印(thisNum)//12

此处所述的
nil
合并运算符是“适合用途”的习惯用法,但作为旁注,您可以通过重载
|
运算符来实现所描述的功能,例如,对于符合某些类型约束的类型。例如,使用
整数
作为类型约束:

extension Bool {
    init<T : Integer>(_ value: T) {
        self.init(value != 0)
    }
}

func ||<T: Integer>(lhs: T, rhs: @autoclosure () -> T) -> T {
    return Bool(lhs) ? lhs : rhs()
}

var thisNum = 0
let thatNum = 12
thisNum = thisNum || thatNum
print(thisNum) // 12
扩展Bool{
初始值(u值:T){
self.init(值!=0)
}
}
func | |(左:T,右:autoclosure()->T)->T{
返回布尔(lhs)?lhs:rhs()
}
var thisNum=0
让thatNum=12
thisNum=thisNum | | thatNum
打印(thisNum)//12

谢谢你的回答,但这比我想要的更具全球效应。谢谢你的回答,但这比我想要的更具全球效应。