mac快速切换大小写_快速模式匹配–如果是大小写,请切换为大小写

本文详细介绍了Swift中的模式匹配,包括在switch语句中的应用,部分匹配元组,配套选配以匹配Optionals,使用〜=运算符进行范围匹配,以及如何与枚举进行模式匹配。通过实例展示了模式匹配在Swift编程中的实用性和灵活性。
摘要由CSDN通过智能技术生成

mac快速切换大小写

In this tutorial, we’ll look into Pattern Matching in Swift. Pattern matching is seen in switch statements.

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

快速模式匹配 (Swift Pattern Matching)

The easy to use switch syntax of Swift can be extended to for and if statements as well.
Pattern matching is used to match tuples, arrays, enums etc. or a part of them.

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

Here’s a very basic example of Pattern matching:

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

for _ in 1...10{
}

Let’s fire up our XCode Playground and start Swifting.

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

部分匹配元组 (Partial Matching Tuples)

In Switch statements, partial matching is very commonly used and implemented as shown below:

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

let author1 = ("Anupam","Android")
let author2 = ("Pankaj","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)

In the above code, we are partially matching only one of the values in the tuple.
Following is the output:

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

Swift Pattern Matching Tuple Partial Output

Swift Pattern Matching Tuple Partial Output

Swift模式匹配元组部分输出

We can write let to each parameter name or like case let as we did in the above snippet.
let is used to bind associated values.

我们可以像上面片段中那样将let写入每个参数名称或类似大小写的let。
let用于绑定关联值。

配套选配 (Matching Optionals)

Swift has a way of matching optionals.
We can do that by using the .some and .none syntax or just setting a ? on the parameter.

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)")
}

if case let x = y is equal to switch y {case let x: }

if case let x = y等于switch y {case let x: }

The output printed in the console is:

控制台中输出的输出为:

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

Let’s look at a switch case example for optional matching:

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

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

Note: if name and password both are nil, the fourth case would be executed.

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

Also, instead of some and none, we can use the following syntax as well:

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

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’s look at the for case to match optionals.

让我们看一下for情况,以匹配可选项目。

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 Pattern Matching Optionals Output

Swift Pattern Matching Optionals Output

Swift模式匹配可选输出

where clause is used to set a pattern matching on the optional case.
where子句用于在可选情况下设置模式匹配。

匹配类型 (Matching Types)

We can match types in the switch statements as shown below:

我们可以在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
    }
}

〜=运算符 ( ~= operator)

We can use the ~= operator in the if statements to match a range as shown below:

我们可以在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!!

The ~= operator can be replaced by = or .contains(age) as well but that would cause readability issues.

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

模式与枚举匹配 (Pattern Matching With Enums)

The last example deals with Pattern matching using Swift Enums.

最后一个示例使用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("Feb 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

This brings an end to this tutorial on Pattern Matching in Swift.

这样就结束了本本Swift模式匹配教程。

翻译自: https://www.journaldev.com/28894/swift-pattern-matching-if-case-for-case-switch-case

mac快速切换大小写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值