Swift -运算符和循环结构
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//赋值符号
//var a = 3
//控制流 (顺序结构, 循环结构, 选择结构)
//循环结构
//for in
for i in -99...99 {
i*i
}
var result = 1
var base = 2
var power = 10
for _ in 1...power {//_忽略值的使用
result *= base
}
result
//for 循环
for var i = -99 ; i <= 99; i++ {//swift3 报错
i*i
}
//while
var aWin = 0
var bWin = 0
var game = 0
while aWin < 3 && bWin < 3 {
game = game + 1
let a = arc4random_uniform(6) + 1
let b = arc4random_uniform(6) + 1
print("a is \(a), b is \(b). ", terminator: "")
if a > b {
print("A win")
bWin = 0
aWin = aWin + 1
}
else if a < b {
print("B win")
bWin = bWin + 1
aWin = 0
}
else {
print("draw")
aWin = 0
bWin = 0
}
}
print("game is \(game)")
repeat - while 至少要执行一次循环
var aWin = false
var bwin = false
repeat {
let a = arc4random_uniform(6) + 1
let b = arc4random_uniform(6) + 1
print("s is \(a), b is \(b).")
if a > b {
aWin = true
}
else if a < b {
bwin = true
}
else {
print("draw ")
}
print("")
}while !aWin && !bwin
let winner = aWin ? "A" : "B"
print("\(winner) win !!")
//选择结构
let poin = (0, 0)
switch poin {
case (0, 0):
print("It is Origin")
fallthrough//允许进入下一个判断语法中
case (_, 0):
print("It is on x-axis")
default:
print("It is just an ordinary point")
}
// x^4 - y^2 = 15*x*y 求一组值
findAnswer:
for m in 1...300 {
for n in 1...300 {
if m*m*m - n*n == 15*m*n {
print(m,n)
break findAnswer
}
}
}
//while
let poin = (3,3)
switch poin {
case let (x, y) where x == y:
print("It is On the line x == y")
case let (x, y) where x == -y:
print("It is On the line x == -y")
default:
print("It is a poin")
}
let age = 19
if case 10...19 = age {
print("You are is a teenager !")
}