Swift学习笔记(三)控制流

前端之家收集整理的这篇文章主要介绍了Swift学习笔记(三)控制流前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.for-in 循环语句

@H_502_4@for index @H_502_4@in 1...5 {
   println("\(index) times 5 is \(index * 5)")
}

2.如果你不需要序列中的每一个值,你可以使用下划线来代替

@H_502_4@let @H_502_4@base = 3
@H_502_4@let power = 10
@H_502_4@var answer = 1
@H_502_4@for _ @H_502_4@in 1...power {
    answer *= @H_502_4@base
}

3.使用for-in去迭代遍历数组

let names = ["Anna","Alex","Brian","Jack"]
@H_502_4@for name @H_502_4@in names {
//    println("Hello,\(name)!")
}

4.for-in去迭代遍历字典

let numberOfLegs = ["spider": 8,"ant": 6,"cat": 4]
@H_502_4@for (animalName,legCount) @H_502_4@in numberOfLegs {
//    println("\(animalName)s have \(legCount) legs")
}

5.for循环 (不能使用let,因为index自增)

@H_502_4@for var @H_502_4@index = 0; @H_502_4@index < 3; ++@H_502_4@index {
    println("index is \(index)")
}

6.If语句

@H_502_4@var temperatureInFahrenheit = 30
@H_502_4@if temperatureInFahrenheit <= 32 {
    println("It's very cold. Consider wearing a scarf.")
}

7.Switch

let someCharacter: Character = "e"
@H_502_4@switch someCharacter {
@H_502_4@case "a","e","i","o","u":
    println("\(someCharacter) is a vowel")
@H_502_4@case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
    println("\(someCharacter) is a consonant")
@H_502_4@default:
    println("\(someCharacter) is not a vowel or a consonant")
}

8.switch元组

let somePoint = (1, 1)
@H_502_4@switch somePoint {
@H_502_4@case (0, 0):
    println("(0,0) is at the origin")
@H_502_4@case (_, 0):
    println("(\(somePoint.0),0) is on the x-axis")
@H_502_4@case (0,_):
    println("(0,\(somePoint.1)) is on the y-axis")
@H_502_4@case (-2...2, -2...2):
    println("(\(somePoint.0),\(somePoint.1)) is inside the Box")
@H_502_4@default:
    println("(\(somePoint.0),\(somePoint.1)) is outside of the Box")
}

9.switch的case中可以使用where

@H_502_4@let yetAnotherPoint = (1,-1)
@H_502_4@switch yetAnotherPoint {
@H_502_4@case @H_502_4@let (x,y) @H_502_4@where x == y:
    println("(\(x),\(y)) is on the line x == y")
@H_502_4@case @H_502_4@let (x,y) @H_502_4@where x == -y:
    println("(\(x),\(y)) is on the line x == -y")
@H_502_4@case @H_502_4@let (x,y):
    println("(\(x),\(y)) is just some arbitrary point")
}
// prints "(1,-1) is on the line x == -y"
原文链接:https://www.f2er.com/swift/326232.html

猜你在找的Swift相关文章