Swift语言简述
来源:互联网 发布:武汉大学罗知 编辑:程序博客网 时间:2024/05/20 05:45
Swift语法
println("Hello, world”)
变量
var myVariable = 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 = "I have \(apples + oranges) pieces of fruit.
创建数组和字典使用方括号([]),并通过在括号内写索引或键访问自己的元素:
数组的赋值:
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
字典的赋值:(key:value结构)
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
字典中某个键的赋值:
occupations["Jayne"] = "Public Relations”
创建一个空的数组:
let emptyArray = String[]()
创建空字典:
let emptyDictionary = Dictionary<String, Float>()
如果类型信息可推断,则可以设置空的数组:shoppingList = []
空字典: shoppingDic=[:]
使用if、switch作为条件判断,使用for-in、for、while、do-while构造循环。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some 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."
}
switch语句支持多种数据和多种比较,若匹配则立即跳出,所以不需要break。
var n = 2
while n < 100 {
n = n * 2
println(n)
}
var m = 2
do {
m = m * 2
println(m)
} while m < 100
这两个程序是等价的,结果都是
4 8 16 32 64 128
其中第一个是swift式的。
var firstForLoop = 0
for i in 0..3 {
firstForLoop += 1
println("第一组+\(firstForLoop)")
}
var secondForLoop = 0
for var i = 0; i < 3; ++i {
secondForLoop += 1
println(secondForLoop)
}
两组程序是等价的,结果:
第一组+1
第一组+2
第一组+3
1
2
3
用..方式设置初始值和最终值。
函数
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
println(greet("Bob", “Tuesday"))
执行结果:Hello Bob, today is Tuesday.
name: String 形式定义变量及类型 ()内用逗号分隔参数,->后跟函数返回类型
学习的资源来自:http://gashero.iteye.com/blog/2075324 以及苹果iBooks。
- Swift语言简述
- Swift闭包简述
- 学习swift《swift简述协议和扩展》
- swift语言,
- swift语言
- swift语言
- Swift语言
- Swift语言
- TCL语言简述
- C语言简述
- 统计语言模型简述
- R语言之简述
- 简述Java语言
- 简述java语言特点
- 简述PHP语言
- 简述YAML语言
- Perl语言简述
- C语言--简述
- 图解Java多态内存分配以及多态中成员方法的特点
- UITableView 滑动一下才刷新数据的解决办法
- app提交的注意事项(争取包过)
- 一些json接口
- Codeforces Round #265 (Div. 2) C.No to Palindromes!
- Swift语言简述
- Swift(1)函数
- Swift(2)数组 array
- 32 低功耗3
- Swift(3)字典
- Swift(4) switch、if & for
- Swift(5)类、结构和属性
- jsp model1模式 制作简易去哪儿网校招界面(四)
- 中断和事件 分不清楚