官方文档百度网盘地址:http://pan.baidu.com/s/1dD8DWrB
答应过群友写这篇文章,下班之后就一定要写。
1. 官方文档的一开始就展示了程序员新语言的入门必写的:hello, world!只不过它是这样写的:
println("Hello, world")
为什么要抛弃main函数和分号?不习惯的说。apple说这样写类似于C和OC,但我总觉得类似java的System.out.println("something"); 你觉得呢?
2.Simple Values
var myVariable = 42
let myConstant = 42
let是常量,而var是变量。那么此处的let是不是可以理解为 int const a = 42 ?这是不指定类型的语法,需要指定类型可以这样 let:int = 42;
3.字符转换
let width = 94
let widthLabel = label + String(width)
从这两行代码中看到了JAVA的 valueOf的感觉。终于不用再写这么长了,解放了劳动力。[NSString stringWithFormat:@"%d",123];
官方例子如下:
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
4. array and dictionary
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations”
最后这行我没看懂,只是赋值吗?谁能解释一下?
新建空字典和数组
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
如果知道是什么类型,可以用[]
声明空数组,用[:]
声明空字典。
后边为什么要跟括号?
“If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.”
苹果的解释还是不太明白。
5.Control Flow
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50
teamScore += 3
else
teamScore += 1
}
teamScore
我熟悉的if (a == a),apple在不断的节约开发时间。最后一行跟了一局teamScore,至今不明白。
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
if 还能这样写if(int a =8)???牛掰!
switch:
“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."
}
这么看起来简练多了。
6. Function
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
放眼望去,满是Lua的感觉。
如果参数不确定可以这样:func sumOf(numbers: Int...);
牛掰的是学人家closure
func a()
{
func b()
{
}
}
闭包:
“numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})”
不了解闭包的可以先去看看JS和Lua对闭包closure的解释。