Swift 基础语法二

// Playground - noun: a place where people can play

import Cocoa

//控制流

//Swift的条件语句包括if和switch,循环语句包含for-in、for、while和do-while,循环/判断条件不需要括号,但循环/判断体(body)必需括号:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    }else{
        teamScore += 1
    }
}

//可空类型
//结合if和let,可以方便的处理可空变量(nullable variable)。对于空值,需要在类型声明后添加?显示标明该类型可空。
var optionalString: String? = "Hello"
optionalString = nil

var optionalName: String? = "John Applesed"
var gretting = "Hello!"
if let name = optionalName{
    gretting = "Hello, \(name)"
}

//灵活的switch
let vegetable = "red pepper"
switch vegetable {
    case "celery":
        let vegetableComment = "Add som raisins and make ants on a log."
    case "cucumber","watercress":
        let vegetableComment = "That would make a good tea sandwich."
    case let x where x.hasSuffix("pepper"):
        let vegetableComment = "Is it a spicy \(x)?"
    default:
        let vegetableComment = "Everything tastes good in soup."
}

//其他循环
//for-in 除了遍历数组也可以用来遍历字典
let interestingNumbers = [
    "Prime":[2,3,5,7,11,13],
    "Fibonacci":[1,1,2,3,5,8],
    "Square":[1,4,9,16,25],
]
var largest = 0
for(kind, numbers) in interestingNumbers{
    for number in numbers{
        if number > largest{
            largest = number
        }
    }
}

//while循环和do-while循环
var n = 2
while n < 100 {
    n = n * 2
}
n

var m = 2
do{
    m = m * 2
}while m < 100
m


//Swift支持传统的for循环,此外也可以通过结合..(生成一个区间)和for-in实现同样的逻辑
var firstForLoop = 0
for i in 0..3{
    firstForLoop += i
}
firstForLoop

var secondForLoop = 0
for var i = 0; i < 3; ++i{
    secondForLoop += 1
}
secondForLoop
//注意:Swift除了..还有... 其中..生成前闭后开的区间,而...生成前闭后闭的区间。
var third = 0
for i in 0...3 {
    third += i
}
third


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值