前言:
从2014年Swift1.0时候开始关注学习,到Swift2.3的时候用Swift帮朋友做过一个项目,后来由于Swift的版本在不断的更新迭代,没有稳定,考虑兼容性问题,公司用的是OC,有一段时间没有碰了,说来惭愧,现在它更新到4.0了。。。下面记录下《A Swift Tour》(Swift4.0初见)
1. 打印
print("hello!")
2.1 常量和变量,用let 表示常量,var表示变量; 编译器可以根据给变量或者常量所赋的值,推断它的数据类型;如果没有给一个变量或者常量赋值,可以指定它的数据类型,用冒号隔开。
let Num = 10
var name = "xiaoming"
name = "lihao"
let explicitFloat:Float
explicitFloat = 70
let explicitDouble: Double = 80
2.2 值不隐式转换,需要显式转换成其他数据类型
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
2.3 字符串里嵌入其他变量,用反斜杠"\"
let apples = 3
let oranges = 5
let myStr = "my"
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) \(myStr)pieces of fruit."
2.4 使用两对3引号表示多行字符串,而且3引号所在行不能有字符串元素。
正确:
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
错误:
let quotation = """I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
错误:
let quotation = """I said "I have \(apples) apples."
And then I said "I have \(apples + oranges)
pieces of fruit." """
2.5 使用[ ]创建数组和字典
1. var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
2. 创建空数组和字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
如果可以推断知道类型信息,可以如下:
shoppingList = [ ]
emptyDictionary = [:]
3 控制语句
3.1 if 语句
let score = 100
if score > 0 {
print("my name is Redin")
}else
{
print("好")
}
输出: my name is Redin
3.2 问号 ? 表示可选变量,即一个变量可能存在也可能为空(nil),可选值可以结合if和let使用,如果可选变量为空(nil),条件判断为false,相反为true。
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
print(greeting)
输出:false 和Hello,John Appleseed
3.3 ?? 处理可选变量,如果可选变量为空(nil),则使用它的默认值
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
注: nickName为可选变量,并且它的值为nil,fullName为默认值,于是informalGreeting的值为"John Appleseed"
3.4 switch, 它不局限于整型,它可以同时用于各种数据类型和各种比较,并且不需要使用break
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
输出:Is it a spicy red pepper?
3.5 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 {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
输出: 25
3.6 while
var n = 2
while n < 100 {
n *= 2
}
print("n:\(n)")
var m = 2
repeat {
m *= 2
} while m < 10
print("m:\(m)")
输出: n:12 m:16
3.7 使用索引遍历:..<(不包含最右边索引值),...(两边索引都包含)
var total1 = 0
for i in 0..<4 {
total1 += i
}
print("total1=\(total1)")
var total2 = 0
for i in 0...4 {
total2 += i
// print("test\(i)")
}
print("total2=\(total2)")
输出:total1=6 total2=10
4 函数和闭包
4.1 使用 func声明一个函数
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
注: 函数名: greet , 参数person和day 是字符串类型, 返回一个字符串
4.1 函数标签, 一般的,函数使用函数参数名作为参数的标签,我们可以自定义一个参数标签放在参数名的前面,或者使用下划线“_”,没有参数标签
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
4.2 元组(tuple), 它可以包含多个参数,表示一个符合值;可以通过元组参数名或索引引用元组的参数。
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum) //参数名引用
print(statistics.2) //索引引用
4.3 函数嵌套,内部函数可以使用外部函数的参数。
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
4.4 函数作为参数使用
1.作为返回参数
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
2.作为函数的参数
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
4.5 闭包,函数其实是一种特殊的闭包,他是一种可以被延迟调用的代码块。通常的,闭包是一个没有名字的代码块。(其内容较多,这里只做简单介绍,以后会专门写一篇讲闭包)
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
5 类和对象,有面向对象编程经验的同学知道,类是对具有相同特点对象的抽象,而对象是对类的具体化。
1. 创建类
class Shape { //shape为对象名
var numberOfSides = 0 //属性变量
func simpleDescription() -> String { //方法
return "A shape with \(numberOfSides) sides."
}
}
//带有init方法
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
2.创建对象
var shape = Shape() //创建
shape.numberOfSides = 7 //属性赋值
var shapeDescription = shape.simpleDescription() //方法调用
var nameShape = NamedShape.init(name: "Redin")
3.继承父类,用override重写父类方法
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
//重写父类NamedShape方法
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
4.setter和getter方法
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
//setter和getter
var perimeter: Double {
get {
return 3.0 * sideLength
}
set(newValue) {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print("value:\(triangle.perimeter)")
triangle.perimeter = 9.9
print("sideLength:\(triangle.sideLength)")
输出:value:9.3 sideLength:3.3
6 枚举和结构体
6.1 枚举,在它的内部定义方法
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
//方法
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
print("ace=\(ace)")
print("aceRawValue=\(aceRawValue)")
print("simpleDescription= \(ace.simpleDescription())")
输出: ace=ace
aceRawValue =1
simpleDescription = ace
6.2 使用init?(rawValue:)
初始化一个枚举 可选变量