Swift4.0基本語法入門

前言:

從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:)初始化一個枚舉 可選變量

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young閱讀 3,874評論 1 10
  • 86.復合 Cases 共享相同代碼塊的多個switch 分支 分支可以合并, 寫在分支后用逗號分開。如果任何模式...
    無灃閱讀 1,421評論 1 5
  • 常量與變量使用let來聲明常量,使用var來聲明變量。聲明的同時賦值的話,編譯器會自動推斷類型。值永遠不會被隱式轉...
    莫_名閱讀 461評論 0 1
  • 與其說越長大越孤單,不如說越長大越害怕孤單。 生活中最常見的低頭族實在大家乘坐的交通工具上,短途的...
    夜雪微瀾閱讀 2,833評論 0 0
  • 建軍九十年沙場大閱兵,看過電視直播,還是不過癮,干脆自己圓一回當兵的夢,穿上軍裝發到朋友圈,男兵英俊瀟灑,女兵颯爽...
    萬象隨心閱讀 204評論 1 0