分类 标签 存档 黑客派 订阅 搜索

Swift 基础部分

96 浏览

其实 Swift 也不是很难, 只不过看起来有点吃力... 一遍看不会, 看两遍, 两遍看不会, 三遍... 直到会背...

//
//  main.swift
//  base
//
//  Created by Adrift on 16/5/28.
//  Copyright © 2016年 Adrift. All rights reserved.
//

import Foundation

//声明变量跟常量
let maxNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
var x = 0.0, y = "hello", z = 10

//类型标注
var welcomeMessage: String
welcomeMessage = "hello world"
var red, green, blue: Double

//常量和变量的命名
let π = 3.14159
let 你好 = "hello world"
let dogcow = "dogcow"
let `let` = "let"
print("\(`let`)")

//元组
let http404Error = (404, "Not fount")
let (statusCode, statusMessage) = http404Error
print("statusCode:\(statusCode),,,statusMessage:\(statusMessage)")
let (justTheStatusCode, _) = http404Error
print("\(http404Error.0)")
print("\(http404Error.1)")

let http200Status = (statusCode: 200, description: "OK")
print("\(http200Status.statusCode)")

var code: Int? = nil

//if语句以及强制解析
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
if convertedNumber != nil {
    print("\(convertedNumber!)")
}

//可选绑定
if let actualNumber = Int(possibleNumber) {
    print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
    print("\(possibleNumber) could not convert to integer")
}
if let firstNumber = Int("3"), secondNumber = Int("2") where firstNumber > secondNumber {
    print("\(firstNumber) > \(secondNumber)")
}

//隐式解析可选绑定
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!//需要感叹号获取值

let assumedString: String! = "An implicitly unwrapped option string"
let implicitString: String = assumedString//不需要感叹号获取值

if assumedString != nil {
    print(assumedString)
}

if let definiteString = assumedString {
    print(definiteString)
}

//错误处理
func canThrowAnError() throws {
    //可能抛出错误
}
do {
    try canThrowAnError()
    //没有错误抛出
} catch {
    //有一个错误消息抛出
}

enum Error: ErrorType {
    case OutOfCleanDishes
    case MissingIngredients
}
func makeASandwich() throws {
    //...
}
do {
    try makeASandwich()
} catch Error.OutOfCleanDishes{
    //washDishes()
} catch Error.MissingIngredients(let ingredients) {
    //buyGroceies(ingredients)
}

//使用断言进行调试
let age = -3
//当表达式结果为false时,结果被显示
assert(age >= 0, "A person's age cannot be less than zero")
assert(age >= 0)//不需要断言信息时,可以省略.

原文地址, 非常感谢翻译者的持续更新.

--EOF--

评论  
留下你的脚步
推荐阅读