之前寫了一些文章發現都不干,所以之后的文章盡量會寫一些干貨。有些同學問我,哥們,你的Swift在哪里學。參考文檔,看博客,視頻嘍。
目錄
- For-In 循環
- While 循環
- 1. For-In 循環
// Created by Hunter on 28/12/2016.
// Copyright ? 2016 Hunter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 輸出閉合區間中的值
for index in 1...5 {
print("index = ",index)
/*輸出
index = 1
index = 2
index = 3
index = 4
index = 5
*/
}
// 不需要變量名,只想循環走5次。可使用下劃線'_'替代變量名字
for _ in 1...5 {
}
// 便利一個數組
let names = ["熊大","熊二","光頭強"]
for name in names {
print("neme:",name)
/*輸出
name: 熊大
name: 熊二
name: 光頭強
*/
}
// 便利一個字典. 注意:字典是無序的
let perssonModel = ["熊大":"18",
"熊二":"12",
"光頭強":"30"]
for (name,age) in perssonModel {
print("name:",name,"age",age)
/*輸出
name: 光頭強 age 30
name: 熊二 age 12
name: 熊大 age 18
*/
}
}
}
- 2. While 循環
兩種形式:
1、 while 當“條件” 成立(true)一直循環執行循環體,當“條件'”不成立(false)跳出循環語句
2、 repeat-while 類似 do-while, 它和while 不同的就是在判斷循環條件是否成立之前,先之心一遍循環體內的代碼,然后若條件成立再執行循環體,直到循環條件不成立,跳出循環體。
While演示
// ViewController.swift
// Swift_Control-Flow
//
// Created by Hunter on 28/12/2016.
// Copyright ? 2016 Hunter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 簡單的例子。
var count = 0
while count < 10 {
count += 1
print(count)
}
print("結束Where循環,count = ",count)
/*輸出
1
2
3
4
5
6
7
8
9
10
結束Where循環,count = 10
*/
/*
具體什么時候用where循環,什么時候用for循環,視具體情況而定,好比官方這個例子,用where循環最合適不過。
就是說當我們并不知道,循環體什么時候結束,只有在達成指定條件是,才結束。這時候我們用where最合適不過。
*/
// 官方例子,滑梯游戲(可參考下方圖片理解圖片(官方例子,滑梯游戲圖片))
let finalSquare = 25
var board = [Int](repeating:0,count:finalSquare+1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
while square < finalSquare {
// 擲骰子
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
// 根據點數移動
square += diceRoll
if square < board.count {
// 如果玩家還在棋盤上,順著梯子爬上去或者順著蛇滑下去
square += board[square]
}
}
print("Game over!",square,diceRoll)
/*輸出
Game over! 27 4
*/
}
}
官方例子,滑梯游戲圖片
do -while 演示
// ViewController.swift
// Swift_Control-Flow
//
// Created by Hunter on 28/12/2016.
// Copyright ? 2016 Hunter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var count = 0
repeat{
count += 1
print(count)
} while count < 0
print("結束Where循環,count = ",count)
/*輸出
1
結束Where循環,count = 1
*/
}
}