首页 > swift中的where在if中怎么用?

swift中的where在if中怎么用?

完整代码

swiftvar optionalHello: String? = "Hello"
if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName {
    greeting = "\(hello), \(name)"
}

在这个片段中对where不是很理解,按照说明“A where clause can be added to a case to further scope the conditional statement”。自己写了如下

swiftvar a = 3
if a<3 where a<10, a>1 {
    print(a)
   }

不出意外会不错啊。
那么问题来了。。。。


mark一下


在if里使用的where是对语句进行一个约束。

if语句执行的是把optionalhello的值赋予常亮hello,如果没有值将为false退出if,而在这个语句里,where执行的是判断可选变量optionalhello的首字母是否为大写'H',如果为false将退出if。

可以理解为是一个嵌套的if语句。

var optionalHello: String? = "Hello"
if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName {
    greeting = "\(hello), \(name)"
}

试验了一下,无论是前面还是后面的where语句,只要其中一个不符合规则,将输出false。

前面的where无法判断后一个段落的值,后面的where可以判断前面一个段落的值。

var op1: String? = "Hello"
var op2: String? = "Swift"
if let hello = op1 where op1 == "Hello" || hello.hasSuffix("o"),
    let name = op2 where name.hasPrefix("S") && hello.hasSuffix("o") {
    println("\(hello),\(name)!")
}else
{
    println("输出失败。")
}

而你写的语法是错误的,如果要使用where必须满足以下几点:
1、被赋的值无论你使用的在之前有没有声明过,跟在if后使用的话必须要重新声明(可以不声明类型只声明变量还是常量)。
2、(a)必须是可选类型,并且在赋值的时,必须是声明过可选类型,如果直接使用a = 1或a = "a",将报错.
4、if里只能用于赋值,不能用于比较大小。

【热门文章】
【热门文章】