“Swift is a powerful and intuitive programming language for macOS,
iOS, watchOS and tvOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.” --苹果官方
苹果自2014年WWDC大会推出swift,到现在越来越多的项目开始使用swift进行开发,所以必须得上车啦!!!
上车啦.jpeg
hello, swift !
print("Hello, world !")
不能坏了规矩不是!哈哈... 如上,就是swift版的“Hello,world !”。注意,末尾没有分号!swift语言不要求在每句代码的后面加分号。当然,你也可以写上。但如果多句代码写在一行,每句代码之间要用分号分割。
print("Hello, world !");print("Hello, swift")
把上面两个print语句之间的分号去掉,会提示如下错误:
Consecutive statements on a line must be separated by ';'
常量和变量
声明常量使用关键字let
,声明变量使用关键字var
。常量值不可被改变,变量值则可以修改。
let constant = 10 // 常量
var variable = 12 // 变量
类型推断
swift是类型安全的。不管是常量还是变量,必须要有一个确定的类型
。如果在声明常量或亦是时进行了初始化,编译器能自动推断出该变量或常量的类型。如果没有初始化,这时需要显式的给常量或变量指明一个类型。
var myVariable = 42 // 编译器根据初始值42自动推断出myVariable是Int型
let implicitDouble = 70.0 // 编译器根据初始值70.0推断出implicitDouble为float型
let explicitDouble: Double = 70 // 可显式指定explicitDouble为Double型
var score: Double // 也可以只声明,不初始化
类型转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
这里String(width)
相当于创建了一个String的实例。+
则用于将两个字符串拼接起来。
使用符号\()
(反斜杠后面跟一括号)也能达到类型转换的目的。
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit.
三个双引号
当字符串内容较多时,可以分多行来写,这时可使用三个双引号"""
括起来。
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""
集合(数组和字典)
/// 声明一个数组变量
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
// 通过索引更改数组的值
shoppingList[1] = "bottle of water"
/// 声明一个字典变量
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
// 新增键值对
occupations["Jayne"] = "Public Relations"
声明空数组和空字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
如果数组或字典的类型已知,可以这样写一个空数组或字典
shoppingList = []
occupations = [:]
流程控制
使用if
和switch
进行条件分支的判断,使用while
,for-in
,repeat-while
书写循环语句。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
注意,if
的条件必须是布尔值,像下面这样就是错的
let score = 60
if score { print("oh yeah !") } // 报错:'Int' is not convertible to 'Bool'
使用if-let
语句处理可选值
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
else {
print("opitionalName is nil")
}
由于变量opitionalName
有初始值,所以程序会走到if
的第一个分支语句里面去。如果opitionalName是nil,才会走到else语句中去。
??
使用符号??
处理可选
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi, \(nickName ?? fullName)"
print(informalGreeting) // Hi, John Appleseed
fullName这里相当于默认值
switch
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.")
}
Dictionary
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)
while && repeat-while
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
range
..<
不包含右边区域最大值;...
包含右边区域最大值。
var total = 0
for i in 0..<4 {
total += i
}
print(total) // 6
var total = 0
for i in 0..<4 {
total += i
}
print(total) // 10
函数和闭包
函数以func
开头,->
用于分割参数和返回值类型。
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
函数调用时默认显示变量名。
函数变量名前加_
,调用时不显示参数名称;若变量名前加参数名称,调用时显示添加的参数名称。
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
函数嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
函数做为返回值
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
函数做为参数
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)
closure(闭包)
关于闭包,先来看看官方是怎么说的:
Closures are self-contained blocks of functionality that can be passed
around and used in your code. Closures in Swift are similar to blocks
in C and Objective-C and to lambdas in other programming languages.
解释一下:闭包就是一个代码块,类似于C和Objective-C中的block。
下面上个简单的栗子:
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
示例中({})内的代码就是一个简单的闭包!
注释
// 这是一行注释
/*
我是多行注释
我是多行注释
*/
/*
多行注释可以嵌套
/*我是嵌套注释*/
/*我是嵌套注释*/
多行注释可以嵌套
*/
类和对象
创建一个Shape类
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
创建一个Shape类的实例
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
Enumerations 枚举
使用enum
创建一个枚举,枚举里面可以定义方法
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
Structures 结构体
创建一个结构体Card
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
由于我是基于苹果的 "The Swift Programing Language(Swift 4)" 文档来学习的,这里也按文档的开始部分来个概述,后面再一一详细展开。有不对的地方,欢迎拍砖!
网友评论