Swift4 快速体验

前言

本章内容完全是描写苹果新语言的基础练习,对于初学者来说是非常好用,好学、升级了编辑器Xcode9快速体验Swift4语法
print("Hello, world!")就是这么简单的打印
该内容基于语法教程,更多内容可以去Develpoer去看API

内容概括

  1. 简单值
  2. 控制流
  3. 函数和闭包
  4. 对象和类
  5. 枚举和结构体
  6. 协议和扩展
  7. 错误处理
  8. 泛型
简单值
  • 使用 let 来声明常量,使用 var 来声明变量。
var myVariable = 42
myVariable = 50
let myConstant = 42
  • 不用明确地声明类型,声明的同时赋值的话,编译器会自动推断类型
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
  • 值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
  • 有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
  • 使用方括号 [] 来创建数组和字典,并使用下标或者键(key)来访问元素。最后一个元素后面允许有个逗号。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
控制流
  • 使用 if 和 switch 来进行条件操作,使用 for-in、 for、 while 和 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)
  • 使用 while 来重复运行一段代码直到不满足条件。循环条件也可以在结尾,保证能至少循环一次。
var n = 2
while n < 100 {
    n = n * 2
}
print(n)

var m = 2
repeat {
    m = m * 2
} while m < 100
print(m)
  • 可以在循环中使用 ..< 来表示范围。
var total = 0
for i in 0..<4 {
    total += i
}
print(total)
函数和闭包
  • 闭包和函数是一个重点,也是难点,比较难学
  • 简单函数比如
func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person:"Bob", day: "Tuesday")
  • 使用元组来让一个函数返回多个值。该元组的元素可以用名称或数字来表示
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)
对象和类
  • 使用 class 和类名来创建一个类。类中属性的声明和常量、变量声明一样,唯一的区别就是它们的上下文是类。同样,方法和函数声明也一样。
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()
枚举和结构体
  • 使用 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
协议和扩展
  • 类、枚举和结构体都可以实现协议。
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
错误处理
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)
}
泛型
  • 在尖括号里写一个名字来创建一个泛型函数或者类型。
func repeatItem<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
repeatItem(repeating: "knock", numberOfTimes:4)

猜你喜欢

转载自blog.csdn.net/yeyu_wuhen/article/details/78905541