Swift模式匹配–如果是大小写,请切换为大小写

时间:2020-02-23 14:44:03  来源:igfitidea点击:

在本教程中,我们将研究Swift中的模式匹配。
在switch语句中可以看到模式匹配。

Swift模式匹配

Swift的易于使用的开关语法也可以扩展为for和if语句。
模式匹配用于匹配元组,数组,枚举等或者其一部分。

这是一个非常基本的模式匹配示例:

for _ in 1...10{
}

让我们启动XCode Playground,开始Swifting。

部分匹配元组

在Switch语句中,部分匹配是非常普遍使用和实现的,如下所示:

let author1 = ("Anupam","Android")
let author2 = ("hyman","Java")
let author3 = ("Anupam","Swift")
let author4 = ("Anupam","Java")

func switchCasePatternTuple(tuple : (String,String))
{

  switch tuple {
  case (let name, "Java"):
      print("\(name) writes on Java")
      
  case let(_,category):
      print("Some author writes on \(category)")
      
  }
}

switchCasePatternTuple(tuple: author1)
switchCasePatternTuple(tuple: author2)
switchCasePatternTuple(tuple: author3)
switchCasePatternTuple(tuple: author4)

在上面的代码中,我们仅部分匹配元组中的值之一。
以下是输出:

Swift模式匹配元组部分输出

我们可以将let写到每个参数名称,或者像上面的代码片段一样写大小写。
" let"用于绑定关联值。

配套选配

Swift有一种匹配可选选项的方法。
我们可以通过使用.some和.none语法或者仅设置?来做到这一点。
在参数上。

let y : Int? = 1
if case .some = y{
  print("Value of optional is \(y)")
}

let x : Int? = 5
if case .some = x{
  print("Value of optional is \(x)")
}

if case .none = x
{
  print("Optional x is nil")
}

if case let z? = x, z>0{
  print("Value of implicitly unwrapped optional is \(z)")
}

如果case let x = y等于switch y {case let x:}

控制台中输出的输出为:

Value of optional is Optional(1)
Value of optional is Optional(5)
Value of implicitly unwrapped optional is 5

让我们看一下可选匹配的开关案例:

let name : String? = "Anupam"
let password : String? = "ABCD"

let userInfo = (name, password)

switch userInfo {
case let (.some(name), .some(password)):
  print("\(name) password is \(password)")
case let (.some(name), nil):
  print("\(name) does not remember the password.")
case (.none, .some(_)):
  print("There is some password but no name.")
case (.none, _):
  print("No user name. No password. ")
}

//prints Anupam password is ABCD

注意:如果名称和密码均为零,则将执行第四种情况。

另外,我们可以使用以下语法来代替某些语法:

switch userInfo {
case let (name?, password?):
  print("\(name) password is \(password)")
case let (name?, nil):
  print("\(name) does not remember the password.")
case (.none, _?):
  print("There is some password but no name.")
case (.none, _):
  print("No user name. No password. ")
}

让我们看一下是否有大小写匹配的可选内容。

let topics =  ["Java","Android","Python","Django","JS",nil]

for case let .some(t) in topics
{
  print("Topic is \(t)")
}

for case let .some(t) in topics where t.starts(with: "J")
{
  print("Topic starting with J is \(t)")
}

Swift模式匹配可选输出

where子句用于在可选情况下设置模式匹配。

匹配类型

我们可以在switch语句中匹配类型,如下所示:

var randomArray: [Any] = ["Swift", 2, 7.5]
for randomItem in randomArray {
  switch randomItem {
  case is Int:
      print("Int value. I don't care about the value")
  case is String:
      print("String type.")
  default: break
  }
}

~=运算符

我们可以在if语句中使用~=运算符来匹配范围,如下所示:

let age = 25

if 0..<13 ~= age{
  print("Hey kid!!")
}
else if 13...19 ~= age{
print("Hey teenager!!")
}
else if 19...45 ~= age{
print("Hey adult!!")
}

//prints Hey adult!!

~=运算符也可以用=或者.contains(age)代替,但这会引起可读性问题。

模式与枚举匹配

最后一个示例使用Swift Enums处理模式匹配。

enum Month{
  case Jan(zodiac: String,gender:String)
  case Feb
  case March(zodiac: String)
}

let month1 = Month.March(zodiac: "Pisces")
let month2 = Month.March(zodiac: "Aries")
let month3 = Month.Jan(zodiac: "Aqarius", gender: "Female")

func switchEnum(month: Month)
{
  switch month {
  case .Feb:
      print("Nov it is")
  case let .March(zodiac) where zodiac == "Pisces":
      print("March Pisces. Aries won't fall here.")
  case let .Jan(_,gender):
      print("Jan does not care about zodiac. Only shows gender \(gender)")
  
  default:
      print("Others")
  }
}

switchEnum(month: month1)
switchEnum(month: month2)
switchEnum(month: month3)

//prints:
//March Pisces. Aries won't fall here.
//Others
//Jan does not care about zodiac. Only shows gender Female