Swift---Swift5基本語法

Swift5 https://docs.swift.org/swift-book/GuidedTour/GuidedTour.htmlhtml

 

import UIKit

var str = "Hello, playground"

//介紹swift5相關的語法


//********************常量和變量
/*
 1.常量定義時必須賦初值,
 2.變量定義時必須加 「!」 or  「?」
 3.能夠在一行中聲明多個常量或者多個變量,用逗號隔開:
 */
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
var x = 0.0, y = 0.0, z = 0.0

var sgfdfd:Int?
var welcomeMessage: String!
var welcomeMessageInt: Int?

var optionalString: String? = "Hello"
print(optionalString == nil)
// Prints "false"

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}


//********************條件語句
//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.")
}
// Prints "Is it a spicy red pepper?"

//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)
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)


//while-repeat
var n = 2
while n < 100 {
    n *= 2
}
print(n)
// Prints "128"

var m = 2
repeat {
    m *= 2
} while m < 100
print(m)
// Prints "128"


//You can keep an index in a loop by using ..< to make a range of indexes.
var total = 0
for i in 0..<4 {
    total += i
}
print(total)










//********************數組和字典
//建立方式一
var shoppingList = ["catfish", "water", "tulips"]
shoppingList[1] = "bottle of water"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
shoppingList.append("blue paint")
print(shoppingList)
//建立方式二
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
let individualScores = [75, 43, 103, 87, 12]
//注意if 語句的使用
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)
// Prints "11"


//********************Functions and Closures
/*
 函數其實是閉包的一種特殊狀況:
 
 
 方法名能夠同樣,可是方法裏的參數設置不能同樣,不然報錯
 */

///簡單方法
func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
func greet(_ person: String, on day: String) -> String {
    return "Hello \(person), today is \(day)."
}
func greet(_ person: String, ooon day: String) -> Int {
    return 15
}
greet(person: "Bob", day: "Tuesday")
greet("John", on: "Wednesday")
greet("Bill", ooon: "TOne")

///返回多個參數的方法[經過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)
// Prints "120"
print(statistics.2)
// Prints "120"



///函數能夠嵌套。嵌套函數能夠訪問在外部函數中聲明的變量。能夠使用嵌套函數在長函數或複雜函數中組織代碼。
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)

///函數其實是閉包的一種特殊狀況:
numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})
///您有幾個選項能夠更簡潔地編寫閉包。當閉包的類型已知時,例如委託的回調,您能夠省略它的參數類型、返回類型,或者二者都省略。單個語句閉包隱式地返回它們惟一語句的值。
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
// Prints "[60, 57, 21, 36]"






//********************Objects and Classes
//一個簡單的類
class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

//一個有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."
    }
    
}
//實現繼承的類
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
    }
    
    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()


///除了存儲的簡單屬性外,屬性還能夠有getter和setter。
class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0
    
    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    }
    
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            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(triangle.perimeter)
// Prints "9.3"
triangle.perimeter = 9.9
print(triangle.sideLength)
// Prints "3.3000000000000003"


///若是您不須要計算屬性,但仍然須要提供在設置新值以前和以後運行的代碼,那麼使用willSet和didSet。只要值在初始化器以外發生更改,就會運行您提供的代碼。例如,下面的類確保三角形的邊長老是與其正方形的邊長相同。
class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
// Prints "10.0"
print(triangleAndSquare.triangle.sideLength)
// Prints "10.0"
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
// Prints "50.0"


///當處理可選值時,您能夠編寫?在方法、屬性和下標等操做以前。若是以前的值是?是nil嗎?被忽略,整個表達式的值爲nil。不然,可選值將被打開,而且在?做用於打開的值。在這兩種狀況下,整個表達式的值都是一個可選值。
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength




//********************Enumerations and Structures
//使用枚舉建立枚舉。與類和全部其餘命名類型同樣,枚舉能夠具備與其關聯的方法。
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
//使用init?(rawValue:)初始化器從原始值生成枚舉的實例。若是沒有匹配的秩,則返回匹配原始值的枚舉用例或nil。
if let convertedRank = Rank(rawValue: 3) {
    let threeDescription = convertedRank.simpleDescription()
}

//枚舉的大小寫值是實際值,而不單單是編寫原始值的另外一種方式。事實上,在沒有有意義的原始值的狀況下,您不須要提供一個。
enum Suit {
    case spades, hearts, diamonds, clubs
    
    func simpleDescription() -> String {
        switch self {
        case .spades:
            return "spades"
        case .hearts:
            return "hearts"
        case .diamonds:
            return "diamonds"
        case .clubs:
            return "clubs"
        }
    }
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
//若是枚舉具備原始值,這些值將做爲聲明的一部分肯定,這意味着特定枚舉用例的每一個實例始終具備相同的原始值。枚舉用例的另外一個選擇是擁有與該用例相關聯的值——這些值是在建立實例時肯定的,而且對於枚舉用例的每一個實例,它們能夠是不一樣的。能夠將關聯值視爲枚舉用例實例的存儲屬性。例如,考慮從服務器請求日出和日落時間的狀況。服務器要麼響應所請求的信息,要麼響應錯誤的描述。

enum ServerResponse {
    case result(String, String)
    case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

switch success {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}
// Prints "Sunrise is at 6:00 am and sunset is at 8:09 pm."



//使用struct建立結構。結構支持許多與類相同的行爲,包括方法和初始化器。結構和類之間最重要的區別之一是,結構在代碼中傳遞時老是被複制,可是類是經過引用傳遞的。
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()





//********************Protocols and Extensions
//使用協議聲明協議。
//使用 mutating 關鍵字修飾方法是爲了能在該方法中修改 struct 或是 enum 的變量,在設計接口的時候,也要考慮到使用者程序的擴展性。因此要多考慮使用mutating來修飾方法。
//注意,在SimpleStructure聲明中使用mutating關鍵字來標記修改結構的方法。SimpleClass的聲明不須要任何標記爲mutating的方法,由於類上的方法老是能夠修改該類。

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription


//使用擴展向現有類型添加功能,如新方法和計算屬性。您能夠使用擴展將協議一致性添加到在其餘地方聲明的類型,甚至添加到從庫或框架導入的類型。
extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)
// Prints "The number 7"

//您能夠像使用任何其餘命名類型同樣使用協議名稱—例如,建立具備不一樣類型但都符合單個協議的對象集合。當處理類型爲協議類型的值時,不能使用協議定義以外的方法。
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
// Prints "A very simple class.  Now 100% adjusted."
// print(protocolValue.anotherProperty)  // Uncomment to see the error
//即便變量protocolValue有一個SimpleClass的運行時類型,編譯器仍然將它視爲給定類型的ExampleProtocol。這意味着除了協議一致性以外,您不能意外地訪問類實現的方法或屬性。



//********************Error Handling
//使用採用錯誤協議的任何類型表示錯誤。
enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}
//使用throw來拋出錯誤,並使用throw來標記可能拋出錯誤的函數。若是在函數中拋出錯誤,函數將當即返回,調用該函數的代碼將處理該錯誤。

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "Job sent"
}
//有幾種方法能夠處理錯誤。一種方法是使用do-catch。在do塊內部,您能夠經過在其前面編寫try來標記可能拋出錯誤的代碼。在catch塊內部,除非您給它一個不一樣的名稱,不然錯誤會自動給出名稱錯誤。
do {
    let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
    print(printerResponse)
} catch {
    print(error)
}
// Prints "Job sent"

//您能夠提供多個catch塊來處理特定的錯誤。在catch以後編寫模式,就像在開關的case以後同樣。
do {
    let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
    print(printerResponse)
} catch PrinterError.onFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}
// Prints "Job sent"

//另外一種處理錯誤的方法是使用try?將結果轉換爲可選的。若是函數拋出錯誤,則丟棄特定的錯誤,結果爲nil。不然,結果是一個可選的,包含函數返回的值。
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")

//使用defer編寫一個代碼塊,該代碼塊在函數中全部其餘代碼以後,即函數返回以前執行。不管函數是否拋出錯誤,都會執行代碼。您能夠使用defer互相編寫安裝和清理代碼,即便它們須要在不一樣的時間執行。
var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]

func fridgeContains(_ food: String) -> Bool {
    fridgeIsOpen = true
    defer {
        fridgeIsOpen = false
    }
    
    let result = fridgeContent.contains(food)
    return result
}
fridgeContains("banana")
print(fridgeIsOpen)
// Prints "false"




//********************泛型
//在尖括號內編寫一個名稱,使其成爲泛型函數或類型。
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
makeArray(repeating: "knock", numberOfTimes: 4)

//您能夠建立函數和方法的通用形式,以及類、枚舉和結構。
// Reimplement the Swift standard library's optional type
enum OptionalValue<Wrapped> {
    case none
    case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)


//在正文前面指定需求列表的位置使用—例如,要求類型實現協議,要求兩種類型相同,或者要求類具備特定的超類。
//sequence 是一個協議
//在 Swift 4 中能夠在 associatedtype 後面聲明的類型後追加 where 語句
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
    where T.Element: Equatable, T.Element == U.Element
{
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}
anyCommonElements([1, 2, 3], [3])
//上面這個假定函數有兩個類型參數。第一個類型參數T,有一個須要T必須遵循Sequence協議的類型約束;第二個類型參數U,有一個須要U必須遵循Sequence協議的類型約束。





print("end")





swift

相關文章
相關標籤/搜索