bwin亚洲必赢5566手机版赶紧看Sample代码,速学Swift语言(1)-语法速览

Swift是苹果推出的一个比较新的言语,它除了借鉴语言如C#、Java等内容他,好像还动用了许多JavaScript脚本里面的一些本子语法,用起来感觉蛮硬,作为一个使用C#长年累月的艺控,对这种比较超前的语言非常感谢兴趣,之前为以上学ES6语法的时节修了阮一峰的《ECMAScript
6
入门》,对JavaScript脚本的ES6报告法写法叹为观止,这种Swift语言也具备众多这种本子语法的风味,可以说此Swift在收到了Object
C的助益并弃一些糟糕的事物外,同时接收了大气初一替代语言的各种特色,包括泛型、元祖等特性。我以上学Swift的早晚,发现合法的语言介绍文章(The
Swift Programming
Language)还是挺浅显易懂,虽然是英文,不过代码和分析说明还挺成功,就是内容展示较多一些,而我们作为技术人员,一般看代码就老好刺探了各种语法特点了,基于此由,我对官网的案例代码进行了一个摘要总结,以代码的法子开展Swift语言的语法特点介绍,总结一词话就是是:快看Sample代码,速学Swift语言。

1、语法速览

var myVariable = 42
myVariable = 50
let myConstant = 42

变量定义用var,常量则用let,类型自行推断。

 

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "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."
"""

代码通过三个对引号来含有预定格式的字符串(包括换行符号),左侧缩进空格省多少。

 

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]()

初始化函数也正如精简。

 

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-else这些跟另外语言没有呀差别,for … in
则是迭代遍历的语法,控制流方式还支持其他的while、repeat…while等不同的语法。

 

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

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

立有些则是不过空类型的以,以及可空判断语句的使,可空判断语句以Swift中使用非常大,这种相当给事先求值再判断是否入大括符语词。

 

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.")
}

Switch语法和例行的语言不同,这种简化了有语法,每个子条件不用显式的描摹break语句(默认就是回的),多个标准逗号分开即可公用一个判断处理。

 

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)

地方字典遍历的章程采用for…in的方开展遍历,另外通过(kind, numbers)的法展开一个参数的解构过程,把字典的键值分别交付kind,numbers这半个参数。

 

var total = 0
for i in 0..<4 {
    total += i
}
print(total)

方的for…in循环使用了一个语法符号..<属于数学半封概念,从0到4,不包含4,同理还有全封闭符号:…全包含左右个别只限之价。

 

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

面是函数的概念,以func关键字定义,括号内是参数的标签、名称及种内容,返回值通过->指定。

点函数需要输入参数名称,如果无欲参数名称,可以通过下扛线省略输入,如下

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

此外参数名称可以应用标签号。

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill!  Glad you could visit from Cupertino."

嵌套函数如下所示。

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

复杂一点的函数的参数可以流传函数进行利用,这种接近闭包的处理了

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)

下是一个闭包的函数,闭包通过in 来分参数和归的函数体

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

 

 

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

恍如的定义通过class关键字展开标识,默认的权杖是internal,在类型模块内部可以拜的,非常好。

利用则如下所示,可以经过接触语法直接获取属性和调用方法。

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

 

class NamedShape {
    var numberOfSides: Int = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

看似经过运用init的指定名称作为构造函数,使用deinit来举行析构函数,使用self来获取当前底好像援,类似于其他语言的this语法,super获取基类的援。

另的处理方式如继续、重写的语法和C#类似。

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()

 

恍如的习性使用get、set语法关键字,和C#类似

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
        }
    }

 

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }

类属性的赋值可以展开察看,如通过willSet在设置前调用,didSet在设置后调用,实现对性能值得监控处理。

 

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

以及类及其他类一样,枚举类型在Swift中还得产生法子定义,是同栽非常灵活的类型定义,这个和我们前面接触了之一般语言有差别。

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)")
}

 

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()

结构类型和类的各个方面很接近,结构支持构造函数,方法定义,属性等,重要一点不同是结构在代码传递的是副本,而接近实例传递的凡接近的援。

 

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

此处的商议,类似很多言语的接口概念,不过比正常语言(包括C#)的接口更加多样化、复杂化一些。

Swift的商事,可以生出一部分方法实现,协议可以可选,继承其他协商等等。

 

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)

推而广之函数通过extension进行标识,可以吧已经有些类进行扩张部分独特的方式处理,这个类似C#的扩充函数。

 

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "Job sent"
}

颇处理面临,函数声明通过throws关键字标识有非常抛来,在函数里面通过throw进行特别抛来处理。

要当拍卖发生充分的地方开展拦截,则通过do…catch的道进行拍卖,在do的言语里面,通过try来遮可能出现的很,默认catch里面的挺名称为error。

do {
    let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
    print(printerResponse)
} catch {
    print(error)
}

可对多单可怜进行判定处理

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)
}

还可以经过采取try?的法子开展协调的良处理,如果发生大返回nil,否者获取结果赋值给变量

let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")

 

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)

应用defer的要紧字来在函数返回前处理代码块,如果来差不多只defer函数,则是后进先出的法展开调用,最后之defer先调用,依次倒序。

 

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)

Swift支持泛型,因此得以大大简化很多函数的编纂,提供更加强大的作用。

enum OptionalValue<Wrapped> {
    case none
    case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)

 

func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    return true
                }
            }
        }
        return false
}
anyCommonElements([1, 2, 3], [3])

泛型的参数支持where的要字展开泛型类型的约束,如得指定泛型的参数采用什么协议要接续哪个基类等等。