swift5.3-day03--条件判断

2020-09-11  本文已影响0人  江山此夜寒

1、算数运算符

Swift中的所有基本类型,我们可以开始使用运算符将它们放在一起。运算符是像+和这样的小数学符号-,而Swift拥有大量的数学符号

let firstScore = 12
let secondScore = 4

let total = firstScore + secondScore
let difference = firstScore - secondScore
let product = firstScore * secondScore
let divided = firstScore / secondScore
let remainder = 13 % secondScore

Swift支持运算符重载,这是一种很好的说法,即运算符的作用取决于您使用它的值

let meaningOfLife = 42
let doubleMeaning = 42 + 42

let fakers = "Fakers gonna "
let action = fakers + "fake"

let firstHalf = ["John", "Paul"]
let secondHalf = ["George", "Ringo"]
let beatles = firstHalf + secondHalf

var score = 95
score -= 5

var quote = "The rain in Spain falls mainly on the "
quote += "Spaniards"

Swift是一种类型安全的语言,这意味着它不会让您混合类型。例如,您不能在字符串中添加整数,因为它没有任何意义。swift取消++和—。

2、比较运算符

let firstScore = 6
let secondScore = 4

firstScore == secondScore
firstScore != secondScore

firstScore < secondScore
firstScore >= secondScore

由于字符串具有自然的字母顺序,因此它们每个都还适用于字符串:

"Taylor" <= "Swift"

3、条件

let firstCard = 11
let secondCard = 10
if firstCard + secondCard == 2 {
    print("Aces – lucky!")
} else if firstCard + secondCard == 21 {
    print("Blackjack!")
} else {
    print("Regular cards")
}

let age1 = 12
let age2 = 21
if age1 > 18 && age2 > 18 {
    print("Both are over 18")
}

4、三元运算符

三元运算符是一个条件,加上一个条件,一个或一个以上的true或false块被一个问号和一个冒号分开

let firstCard = 11
let secondCard = 10
print(firstCard == secondCard ? "Cards are the same" : "Cards are different")

5、swich语句

let weather = "sunny"
switch weather {
case "rain":
    print("Bring an umbrella")
case "snow":
    print("Wrap up warm")
case "sunny":
    print("Wear sunscreen")
default:
    print("Enjoy your day!")
}

最后一种情况default是必需的-因为Swift会确保您涵盖所有可能的情况,因此不会错过任何可能的情况。如果天气不是下雨,下雪或晒日光,default则将运行机箱。

Swift只会在每种情况下运行代码。如果要继续执行下一种情况,请使用如下fallthrough关键字

switch weather {
case "rain":
    print("Bring an umbrella")
case "snow":
    print("Wrap up warm")
case "sunny":
    print("Wear sunscreen")
    fallthrough
default:
    print("Enjoy your day!")
}

5、范围运算符

Swift提供了两种生成范围的方式:..<...运算符。半开范围运算符,..<创建范围不超过最终值,但不包括最终值;封闭范围运算符...,创建范围不超过最终值,包括最终值。

例如,范围1..<5包含数字1、2、3和4,而范围1...5包含数字1、2、3、4和5。

范围对于switch块很有用,因为您可以在每种情况下使用它们。

let score = 85

switch score {
case 0..<50:
    print("You failed badly.")
case 50..<85:
    print("You did OK.")
default:
    print("You did great!")
}
上一篇下一篇

猜你喜欢

热点阅读