Swift学习笔记一-简单值和控制流

学习了IOS这么久,都没有认真了解过Objective-C这门语言,现在从头开始学习Swift.听说以后Android用Swift作为开发语言呀,这NM让Android小伙伴情何以堪…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//
// main.swift
// 简单值,控制流
//
// Created by Adrift on 16/4/17.
// Copyright © 2016年 Adrift. All rights reserved.
//

import Foundation

//## ###### #简单值## ######

//显式声明常量
let x:Float = 40
print("\(x) hello world")
//显式声明变量
var label:String = "the width is"
//隐式声明变量
var width = 78
//类型转换
var widthLabel = label + String(width)

//声明数组
var persons = ["xiaoming","xiaohong"]
print(persons[0])
//声明字典
var person = [
"name":"xiaogang",
"age":12
]
print(person["age"])

//数组跟字典初始化方法
let emptyArr = [String]()//后面加个括号是什么鬼?数组长度么?
let emptyDic = [String:Float]()

//如果类型可以推断出来可以用[]跟[:]
let emptyArr1 = []
let emptyDic1 = [:]

//## ###### #控制流## ###### #
//###### #if###### #
//用if,switch进行条件操作,用for,for-in,while,repeat-while进行循环.包裹条件和循环变量的括号可以省略,但是语句体的大括号是必须的.
let individualScores = [75,43,103]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
//在if语句中,条件必须是一个布尔表达式
var optionalString:String? = "hello"
print(optionalString == nil)

var optionalName:String? = nil
var greeting:String
if let name = optionalName {
greeting = "hello," + name
//swift的代码规范做的很好,代码一不规范就给你报错,没脾气.不知道是故意做的规范呢?还是没有优化好呢?下面的else语句就不会出现这种问题
//"hello,"+ name跟"hello," +name会报错
}else {
//name的值在这是取不到的.
//greeting = "hello," + name
}
//另一种处理可选值的方式使用??操作符提供默认值,如果可选值为nil,用默认值代替
let nickName:String? = nil
let fullName:String = "Adrift Jing"
let informalGreeting = "hello \(nickName ?? fullName)"//这也必须得加空格
print(informalGreeting)

//###### #switch###### #
//switch支持任意类型以及各种比较操作--不仅仅是整数以及测试相等
let vegetable:String = "red pepper"
//vegetable不能是可选值,switch中必须包含default,不然会报错
//执行到匹配的case语句,会退出switch语句,并不用写break
switch vegetable {
case "celery","watercress":
print("hello world");
case let x where x.hasPrefix("red pepper"):
print(x);
default:
print("everyting")
}

//## ##for-in###### ###
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 {
print(kind)
if kind != "Square" {
for number in numbers {
if number > largest {
largest = number
}
}
}
}
print("largest is "+String(largest))

//## ##while###### #
//使用while来重复运行一段代码直到不满足条件.循环条件也可以在结尾,保证至少能循环一次.
var n = 2
while n < 100 {
n = n * 2
}
print(n)

var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
//可以在循环中使用..<表示范围. ..<创建的范围不包含上界,如果需要的话使用...
var total1 = 0
for i in 0..<4 {
total1 += i;
}
print(total1);
var total2 = 0
for x in 0...4 {
total2 += x
}
print(total2)

–EOF—