println("Hello,world”)
//var定义变量 let定义常量
varmyVariable = 42
myVariable = 50
let myConstant = 42
//定义常量或变量的时候指定类型
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
//定义字符串
let label = "The width is “
let width = 94
let widthLabel = label + String(width)
//在字符串中添加值
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples”
let fruitSummary = “Ihave \(apples + oranges) pieces of fruit.”
//创建字典和数组
var shoppingList = ["catfish","water","tulips","blue paint”]
shoppingList[1] = "bottle of water”
var occupations = [
"Malcolm": "Captain”,
"Kaylee": "Mechanic”,
]
occupations["Jayne”] ="Public Relations”
//创建空数组和空字典
let emptyArray = String[]()
let emptyDictionary =Dictionary<String,Float>()
//for in 语句
let individualscores =[75,43,103,87,12]
for index in individualscores {
println("\(index) times 5 is \(index * 5)")
}
let numberOfLegs = ["spider": 8,"ant": 6,"cat": 4]
for (animalName,legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
for character in "Hello" {
println(character)
}
//for循环
for var index = 0; index < 3; ++index {
println("index is \(index)")
}
//while
var square = 0
var diceRoll = 0
while square < finalSquare {
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
if square < board.count {
// if we're still on the board,move up or down for a snake or a ladder
square += board[square]
}
}
println("Game over!")
//if else
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
//switch case
64
//问号 感叹号
!告诉编译器这个变量绝对不为nil,当为nil的时候会报错
?告诉编译器这个变量可能为nil,当为nil的时候不会报错
//创建单例
import UIKit
class
DataCenter:
NSObject
{
let dataCenterObj:DataCenter = DataCenter()
func getDataCenter() ->DataCenter {
return
dataCenterObj
}
}
6.协议(Protocols)
语法:
在Objective-C中我们这么声明Protocol:
1
2
3
|
@protocolSampleProtocol
-(void)someMethod;
@end
|
而在Swift中:
3
4
{
funcsomeMethod()
}