println("Hello, world")
输出结果:
Hello, world
swift使用let来声明常量,使用var来声明变量
//变量
var myVariable = 42
myVariable = 50
//常量
let myConstant = 42
如果初始值没有提供足够的信息(或者没有初始值),那你需要在变量后面声明类型,用冒号分割
let implicitInteger = 70
let implicitDouble = 70.0
//此处声明explicitDouble是double类型的常量
let explicitDouble: Double = 70
类型转换
let label = "The width is"
let width = 94
//嘿嘿,很类似java的强制类型转换
let widthLabel = label + String(width)
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
swift数组:
类似java数组
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[0] = "catfish"
shoppingList[1] = "water"
shoppingList[2] = "tulips"
shoppingList[3] = "blue paint"
swift空数组
let emptyArray = String
let emptyDictionary = Dictionary
控制流
java中常见的if..else{...},while,do ...while...,for...在swift中是如何表示的,请往下看:
在数组[75, 43, 103, 87, 12],如果数组中的内容>50,
teamScore+3;否则teamScore+1;
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
teamScore
switch语句:
let vegetable = "red pepper"
switch vegetable {
//vegetable=celery的话
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
//vegetable=celery的话或者watercress
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
//字符串中有pepper话执行
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
//上面条件都不符合,执行如下代码
default:
let vegetableComment = "Everything tastes good in soup."
}
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
println("The letter a")
case "A":
println("The letter A")
default:
println("Not the letter A")
}
(没看懂,)
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
}
}
}
largest
while和do while
swift的循环相比java看起来好奇葩
初始值为2,便利100以内的值,n=100以内的值逐个*2递增
var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
do {
m = m * 2
} while m < 100
m
0->3的求和操作,初始值为0
var firstForLoop = 0
for i in 0..3 {
firstForLoop += i
}
firstForLoop
var secondForLoop = 0
for var i = 0; i < 3; ++i {
secondForLoop += 1
}
secondForLoop
明日计划:
看函数和闭包