Swift4.0基本語法入門

前言:

從2014年Swift1.0時(shí)候開始關(guān)注學(xué)習(xí),到Swift2.3的時(shí)候用Swift幫朋友做過一個(gè)項(xiàng)目,后來由于Swift的版本在不斷的更新迭代,沒有穩(wěn)定,考慮兼容性問題,公司用的是OC,有一段時(shí)間沒有碰了,說來慚愧,現(xiàn)在它更新到4.0了。。。下面記錄下《A Swift Tour》(Swift4.0初見)

1. 打印

print("hello!")

2.1 常量和變量,用let 表示常量,var表示變量; 編譯器可以根據(jù)給變量或者常量所賦的值,推斷它的數(shù)據(jù)類型;如果沒有給一個(gè)變量或者常量賦值,可以指定它的數(shù)據(jù)類型,用冒號(hào)隔開。

let  Num = 10
var name = "xiaoming"
name = "lihao"
let  explicitFloat:Float 
explicitFloat = 70
let explicitDouble: Double = 80

2.2 值不隱式轉(zhuǎn)換,需要顯式轉(zhuǎn)換成其他數(shù)據(jù)類型

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引號(hào)表示多行字符串,而且3引號(hào)所在行不能有字符串元素。

正確:
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
錯(cuò)誤:
let quotation = """I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
錯(cuò)誤:
let quotation = """I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) 
pieces of fruit." """

2.5 使用[ ]創(chuàng)建數(shù)組和字典

1. var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

2. 創(chuàng)建空數(shù)組和字典
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 問號(hào) ? 表示可選變量,即一個(gè)變量可能存在也可能為空(nil),可選值可以結(jié)合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),則使用它的默認(rèn)值

let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

注: nickName為可選變量,并且它的值為nil,fullName為默認(rèn)值,于是informalGreeting的值為"John Appleseed"

3.4 switch, 它不局限于整型,它可以同時(shí)用于各種數(shù)據(jù)類型和各種比較,并且不需要使用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 遍歷數(shù)組和字典

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 函數(shù)和閉包

4.1 使用 func聲明一個(gè)函數(shù)

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")

注: 函數(shù)名: greet , 參數(shù)person和day 是字符串類型, 返回一個(gè)字符串

4.1 函數(shù)標(biāo)簽, 一般的,函數(shù)使用函數(shù)參數(shù)名作為參數(shù)的標(biāo)簽,我們可以自定義一個(gè)參數(shù)標(biāo)簽放在參數(shù)名的前面,或者使用下劃線“_”,沒有參數(shù)標(biāo)簽

func greet(_ person: String, on day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")

4.2 元組(tuple), 它可以包含多個(gè)參數(shù),表示一個(gè)符合值;可以通過元組參數(shù)名或索引引用元組的參數(shù)。

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) //參數(shù)名引用
print(statistics.2) //索引引用

4.3 函數(shù)嵌套,內(nèi)部函數(shù)可以使用外部函數(shù)的參數(shù)。

func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()

4.4 函數(shù)作為參數(shù)使用

1.作為返回參數(shù)
func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
increment(7)

2.作為函數(shù)的參數(shù)

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 閉包,函數(shù)其實(shí)是一種特殊的閉包,他是一種可以被延遲調(diào)用的代碼塊。通常的,閉包是一個(gè)沒有名字的代碼塊。(其內(nèi)容較多,這里只做簡單介紹,以后會(huì)專門寫一篇講閉包)

numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})

5 類和對象,有面向?qū)ο缶幊探?jīng)驗(yàn)的同學(xué)知道,類是對具有相同特點(diǎn)對象的抽象,而對象是對類的具體化。

1. 創(chuàng)建類
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.創(chuàng)建對象
var shape = Shape()  //創(chuàng)建
shape.numberOfSides = 7  //屬性賦值
var shapeDescription = shape.simpleDescription()  //方法調(diào)用
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 枚舉和結(jié)構(gòu)體

6.1 枚舉,在它的內(nèi)部定義方法

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容