//常量和变量
var myNumber = 42
let myConst = 32
var myVar:Double = 20
let myFloat:Float = 15
//字符串
let label = "hello width"
let width = 20
let widthLabel = label+String(width)
print(widthLabel)
//值转为字符串,直接使用反斜杠转换\()
let apples = 3
let oringle = 5
let applesummary = "i have \(apples)"
print(applesummary)
//数组,直接赋值
var fruitList = ["apple","oriangle","banana"]
print(fruitList)
//创建空数组
let emptyArray = [String]()
print(emptyArray)
//字典,27)"> var fruitDis = ["1":"apple","2":"orignale"]
print(fruitDis)
//创建空字典
let emptyDic = [String]()
print(emptyDic)
//控制流if,switch,for-in for while repeat-while
//需要注意的是它们之间的空格必须要有.并且在if语句中,条件必须要是一个布尔表达式,系统不会默认给判断
let indiviNumber = [11,21,31,41]
var teamscore = 0
for score in indiviNumber{
if score > 21
{
teamscore += 1
}else{
teamscore += 2
}
}
print(teamscore)
//这里加一个问号是说明可选字符串
var optionString:String? = "lihuan"
print(optionString == nil)
//switch语句
let vegetable = "red pepper"
switch vegetable {
case "apple":print("hello")
case "red pepper":print("right")
default:print("wrong")
}
//for in 遍历的使用,遍历字典
let intestNumber = ["prime":[1,2,3,4],"fibonacci":[5,6,7,8],]
var largest = 0
for(kind,numbers) in intestNumber {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
//while 的使用
var n = 2
while n < 100 {
n = n*2
}
print(n)
//repeat-while的使用
var m = 5
repeat {
m = m*5
} while m < 100
print(m)
//for 循环
var loopNumber = 0
for i in 0..<4 {
loopNumber += i
}
print(loopNumber)
//另一种写法,不建议使用
var loopSecond = 0
for var i = 0; i < 4; ++i {
loopSecond += i
}
print(loopSecond)
// 函数和闭包
// 使用func 来生明,使用名字和参数来调用函数 使用 -> 来指定函数返回值的类型
//greet是函数名,name和day是变量 void是返回值类型
func greet (name:String,day:String) -> Void {
print ("hello \(name),today is \(day)")
}
//使用函数
greet("lee",day:"monday")
//计算参数平均值方法
func avergae (numbers:[Double],index:Int) -> Double {
var sum:Double = 0
for number in numbers {
sum += number
}
return sum/Double(index)
}
print(avergae([1,2.3,3],index: 3))
原文链接:https://www.f2er.com/swift/324045.html