Swift_Apprentice_v2.0语法上
2017-07-03 本文已影响81人
Mg明明就是你
-
一、第一部分:
-
1.Playgrounds overview
76EC2ADC-AA6C-43AD-9A57-2C08844F059C.png
- 1.Source edit:r这是你要写你的Swift代码的地方。它就像一个文本编辑器,如记事本或TextEdit。您会注意到使用了所谓的单空间字体,这意味着所有的字符都是相同的宽度。这使得代码更易于阅读和格式化。
- 2.Results sidebar:结果侧栏将是您将确认您的代码是否正常工作的主要地方
- 3.Execution control:默认情况下,playground会自动执行,这意味着你可以编写代码并立即看到输出。这个控制允许你再次执行操场。按住按钮允许您在自动执行和手动执行模式之间切换。
- 4.Activity viewer:这显示了playground的状态。在Inthescreenshot中,它显示了操场已经完成了,并且准备在源代码编辑器中处理更多的代码。当操场执行时,这个观察者将用一个旋转器来表示这个。
- 5.Panel controls:这些切换开关显示并隐藏了三个面板,一个出现在左边,一个在底部,一个在右边。这些面板显示了您可能需要不时访问的额外信息。你通常会把它们隐藏起来,就像它们在截图中一样。
-
二、第二部分Expressions
-
1.The operators for these two operations are as follows:
-
1.操作符
-
Shiftleft:<<
-
Shiftright:>>
-
说明是以2进制进行移动,9<<1=92=18,6<<2=62=24,9>>1=9/2=4(取整)
-
2.Math functions
sin(45 * Double.pi / 180)
// 0.7071067811865475
cos(135 * Double.pi / 180)
// -0.7071067811865475
sqrt(2.0) //根号
// 1.414213562373095
max(5, 10) // 两者中取最大值
// 10
min(-5, -10) // 两者中取最小值
// -10
max(sqrt(2.0), Double.pi / 2)
// 1.570796326794897
如果一个字符串0的个数太多你很难数出写了几个0的话,你可以这样
5A7DBBB1-1734-4B99-9127-D093FD231018.png
-
三、第三部分:Types & Operations类型和操作
Tuples元组
tuple是表示由任何类型的多个值组成的数据的类型。您可以在tuple中拥有任意多的值。
例如,您可以定义一对2D坐标,其中每个轴值都是一个整数,如下所描述的:
-
Dictionary(字典)
var namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
namesAndScores.isEmpty // false
namesAndScores.count // 4
Array(namesAndScores.keys) // ["Craig", "Anna", "Donna","Brian"]
Array(namesAndScores.values) // [8, 2, 6, 2]
// 根据key更新值
namesAndScores.updateValue(6, forKey: "Brian") //
print(namesAndScores["Brian"]) // 6
// There’s even a shorter way to add pairs, using subscripting: 添加键值对
bobData["city"] = "San Francisco"
// Removing pairs:移除键值对
namesAndScores.removeValue(forKey: "Anna")
// 该方法将从字典中删除键状态及其关联值。
// 如您所料,使用下标更短的方法来实现这一点:
namesAndScores["Donna"] = nil
-
Iterating through dictionaries(字典遍历)
var namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
for (player, score) in namesAndScores {
print("\(player) - \(score)")
}
// > Craig - 8
// > Anna - 2
// > Donna - 6
// > Brian - 2
for player in namesAndScores.keys {
print("\(player)")
}
// > Craig, Anna, Donna, Brian
-
四、第四部分:Basic Control Flow(流程控制)
Bool:TRUE AND FALSE
let a = 5
let b = 10
let min: Int
if a < b { min = a } else { min = b }
let max: Int
if a > b { max = a } else {max = b }
-
三目运算符:(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>
let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b
-
While loops(循环)先判断条件再执行
while <CONDITION> {
<LOOP CODE>
}
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1) // 1023
}
解释:
• Afteriteration2:sum=7,loopcondition=true•
• Afteriteration3:sum=15,loopcondition=true • •Afteriteration4:sum=31,loopcondition=true • •Afteriteration5:sum=63,loopcondition=true • •Afteriteration6:sum=127,loopcondition=true•
• Afteriteration7:sum=255,loopcondition=true•
• Afteriteration8:sum=511,loopcondition=true•
• Afteriteration9:sum=1023,loopcondition=false•
-
Repeat-while loops (先执行再判断条件)
repeat {
<LOOP CODE>
} while <CONDITION>
var sum = 1
repeat {
sum = sum + (sum + 1) // 1023
} while sum < 1000
-
Breaking out of a loop
var sum = 1
while true {
sum = sum + (sum + 1)
if sum >= 1000 {
break // 当sum >= 1000调出循环
}
}
-
For loops
for <CONSTANT> in <RANGE> {
<LOOP CODE>
}
-
eg1: for
var sum = 0
for row in 0..<8 {
if row % 2 == 0 {
continue
}
for column in 0..<8 {
sum += row * column
}
}
-
eg2: for
var sum = 0
rowLoop: for row in 0..<8 { // 给行循环起一个名字rowLoop
columnLoop: for column in 0..<8 { // 给列循环起一个名字columnLoop
if row == column { // 如果行数等于列数
continue rowLoop // 不执行此次行的循环
}
sum += row * column
}
}
- eg3: for遍历
for index in stride(from: 10, to: 22, by: 4) {
print(index)
}
// prints 10, 14, 18
for index in stride(from: 10, through: 22, by: 4) {
print(index)
}
// prints 10, 14, 18, and 22
-
Switch statements
let number = 10
switch number {
case 0:
print("Zero")
default:
print("Non-zero")
}
-
Advanced switch statements
let hourOfDay = 12
let timeOfDay: String
switch hourOfDay {
case 0, 1, 2, 3, 4, 5:
timeOfDay = "Early morning"
case 6, 7, 8, 9, 10, 11:
timeOfDay = "Morning"
case 12, 13, 14, 15, 16:
timeOfDay = "Afternoon"
case 17, 18, 19:
timeOfDay = "Evening"
case 20, 21, 22, 23:
timeOfDay = "Late evening"
default:
timeOfDay = "INVALID HOUR!"
}
// 优化写法
switch hourOfDay {
case 0...5:
timeOfDay = "Early morning"
case 6...11:
timeOfDay = "Morning"
case 12...16:
timeOfDay = "Afternoon"
case 17...19:
timeOfDay = "Evening"
case 20..<24:
timeOfDay = "Late evening"
default:
timeOfDay = "INVALID HOUR!"
}
-
Partial matching(部分匹配)
let coordinates = (x: 3, y: 2, z: 5)
switch coordinates {
case (0, 0, 0): // 1
print("Origin")
case (_, 0, 0): // 2
print("On the x-axis.")
case (0, _, 0): // 3
print("On the y-axis.")
case (0, 0, _): // 4
print("On the z-axis.")
default: // 5
print("Somewhere in space")
}
// 更进一步
let coordinates1 = (x: 3, y: 6, z: 4)
switch coordinates1 {
case (0, 0, 0):
print("Origin")
case (let x, 0, 0):
print("On the x-axis at x = \(x)")
case (0, let y, 0):
print("On the y-axis at y = \(y)")
case (0, 0, let z):
print("On the z-axis at z = \(z)")
case let (x, y, z):
print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}
// Somewhere in space at x = 3, y = 6, z = 4
// let coordinates1 = (x: 3, y: 0, z: 0) On the x-axis at x = 3
// let coordinates1 = (x: 0, y: 6, z: 0) On the y-axis at y = 6
// let coordinates1 = (x: 0, y: 0, z: 4) On the z-axis at z = 4
-
五、第五部分:Function(函数)
Function parameters(带参函数)
func printMultipleOf(multiplier: Int, andValue: Int) {
print("\(multiplier) * \(andValue) = \(multiplier * andValue)")
}
printMultipleOf(multiplier: 4, andValue: 2) // 4 * 2 = 8
-
default values to parameters(默认参数)
func printMultipleOf(_ multiplier: Int, _ value: Int = 1) {
print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4)// 4 * 1 = 4
-
Return values(返回参数)
func multiply(_ number: Int, by multiplier: Int) -> Int {
return number * multiplier
}
let result = multiply(4, by: 2) // 8
-
Advanced parameter handling
// 错误示范
func incrementAndPrint(_ value: Int) {
value += 1
print(value)
}
var value = 5
incrementAndPrint(value) // 报错了,如下
This results in an error:
Left side of mutating operator isn't mutable: 'value' is a 'let' constant
func incrementAndPrint(_ value: inout Int) {
value += 1
print(value)
}
var value = 5
incrementAndPrint(&value)
print(value) // 6
-
Overloading(重载,OC不行吶)
-
eg1:举个栗子
-
func printMultipleOf(multiplier: Int, andValue: Int){}
func printMultipleOf(multiplier: Int, and value: Int){}
func printMultipleOf(_ multiplier: Int, and value: Int){}
func printMultipleOf(_ multiplier: Int, _ value: Int){}
-
eg2:举个🌰
func getValue() -> Int {
return 31;
}
func getValue() -> String {
return "Matt Galloway"
}
let value = getValue()
// 报错
error: ambiguous use of 'getValue()'
// 需明确类型
let valueInt: Int = getValue() // 31
let valueString: String = getValue() // "Matt Galloway"
-
Functions as variables(给方法取个名字)
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
var function = add
function(4, 2) // 6
func subtract(_ a: Int, _ b: Int) -> Int {
return a - b
}
function = subtract
function(4, 2) // 2
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
let result = function(a, b) // 6
print(result)
}
printResult(add, 4, 2) // 6
轻轻点击,关注我简书
轻轻点击,关注我简书
轻轻点击,关注我微博
浏览我的GitHub
扫一扫,关注我.jpg
扫一扫,关注我