目录
前言 3
Introducing to Swift 4
ARRAYS,DICTIONARIES,LOOPS,SWITCH CASE 5
OPTIONALS 6
ENUMERATION 7
STRUCTS 8
CLASSES 9
PROPERTIES 10
ACCESS CONTROL 11
POLYMORPHISM AND TYPE CASTING 12
CLOSURES 13
前言
原文:-with-swift-xue-xi-bi-ji/
Hacking with Swift 是由 Paul Hudson 发布的免费 Swift 教程,其涵盖了30个项目,并且包含了 Swift 。因为该教程是面向初学者,所以很多知识点都没有深入探讨,如果想要深入学习可以参考官方文档:The Swift Programming Language (Swift )
Introducing to Swift
Introducing to Swift
Playground 是自 Xcode6 起苹果加入的实时浏览代码结果的一个功能。
变量通过 var 声明,常量通过 let 声明。 Swift 可以推断变量的类型(type reference),所以声明变量可以直接如下:
var string = “My string”
//也可以先声明类型(必须)或声明与赋值同时:
var string:String = “My string”
苹果官方建议在声明有小数部分的变量时都采用 Double,因其具有更高的精准度。
Swift 中 bool 值是 true 和 false。
“+”号也可用于 string :
var name1 = "Tim McGraw"
var name2 = "Romeo"
var both = name1 + " and " + name2 //"Tim McGraw and Romeo"
字符串的对比运算是”case-sensitive”,也就是区分大小写:
var name = “TIM MCGRAW"
var name2 = "TiM mCgRaW"
name == name2 //result is false
在 string 中插入变量:
var name = “Tim McGraw”
“Your name is \(name)”
//可以在括号中运算:
var age = 25
“His age is \(age * 2)”
ARRAYS,DICTIONARIES,LOOPS,SWITCH CASE
ARRAYS,DICTIONARIES,LOOPS,SWITCH CASE
通过类型注释(Type annotaions)可以申明数组内容的类型:
var songs: [String] = ["Shake it Off", "You Belong with Me", "Back to December", 3]
//以上会报错,因为数组内有非 String 类型的”3”在内。
以下代码仅仅是声明了一个将要被分配包含String对象数组的变量:
var array:[String]
//没有真正创建数组对象
var array: [String] = []
//这时才是创建了数组对象
var array = [String] ()
//效果同上,语法更为简洁。
数组可以直接使用”+”运算符结合:
var songs = ["Shake it Off", "You Belong with Me", "Love Story"]
var songs2 = ["Today was a Fairytale", "White Horse", "Fifteen"]
var both = songs + songs2
both += [“Everything”]
//可以增加并赋值
创建一个 Disctionary:
var person = [
"first": "Taylor",
"middle": "Alison",
"last": "Swift",
"month": "December",
"website": ""
]
Swift 中,条件表达式不需要括号:
if person == "hater" {
action = "hate"
} else if perso
HackingWithSwift学习笔记 来自淘豆网m.daumloan.com转载请标明出处.