import Foundation
//***********************************************************************************************
//1.Hello world
//_______________________________________________________________________________________________
//输出 "Hello, world"
println("Hello, world") //使用 println 函数来输出字符串
//***********************************************************************************************
//2.Simple Values(简单值)
//_______________________________________________________________________________________________
//使用 let 命名常量,使用 var 命名变量
let myConstant =42
var myVariable =42
myVariable = 50
println("The constant is(myConstant),the variable is(myVariable)")
//_______________________________________________________________________________________________
//声明数据类型
let explicitDouble:Double = 70
println("The Double type number is(explicitDouble)")
//_______________________________________________________________________________________________
//类型转化
let label = "The width is "
let width =94
let widthLabel = label + String(width) //不同类型数据进行基本运算的时候须要进行类型转化
println(widthLabel)
//_______________________________________________________________________________________________
//简单的字符串引用数据
let apples =3
let appleSummary ="I have (apples) apples"
println(appleSummary)
//_______________________________________________________________________________________________
//数组创建和使用
var shoppingList = ["water","bread", "milk","paper", "pen"]
println(shoppingList[2]) //获取数组中的第三个元素
//_______________________________________________________________________________________________
//字典的创建和使用
var occupations = ["Malcolm":"Captain", "Kaylee":"Mechanic"]
occupations["Jayne"] ="Public relations" //给字典加入或者改动一个元素。系统检索字典 occupations是否包括 key 值 Jayne,假设有进行 key 相应的 value 值的改动,假设没有,进行新的 key和 value 的加入
println(occupations)
//_______________________________________________________________________________________________
//创建空的数组和字典
let emptyArray = [String]() //创建空的数组
let emptyDictionary =Dictionary<String,Float>() //创建空的字典
//***********************************************************************************************
//3.Control Flow(控制流)
//_______________________________________________________________________________________________
//简单的控制语句
let individualScores = [75,43, 103, 87, 12]
var teamScore =0
for score inindividualScores{
if score > 50{ //if 语句之后必须为返回一个 Bool类型的数据
teamScore += 3
}
else{
teamScore += 1
}
}
println("The teamscore is(teamScore)")
//_______________________________________________________________________________________________
//可选类型数据
var optionalString:String?
= "Hello"
optionalString == nil //设置 optionalString数据为可选类型数据,可选类型是指 optionalString有详细的值或者为空两种情况
var optionalName:String? = "Joho Appleseed"
var greeting ="Hello"
if let name =optionalName{ //使用 if let 来推断可选类型数据是否有详细的值
greeting = "Hello,(name)"
}
println(greeting)
//_______________________________________________________________________________________________
//switch 语句
let vegetable ="red pepper"
var vegetableComment:String
switch vegetable{ //使用 switch 语句。每一条 case 代表一条推断。符合条件则运行语句
case"celery":
vegetableComment ="Add some raisins and make ants on a log."
case"cucumber","watercress":
vegetableComment ="That would make a good tea sandwich."
caselet x where x.hasSuffix("pepper"): //使用 "x.hasSuffix("***")"函数来推断 x 变量末尾是否为 ***
vegetableComment ="Is it a spicy (x)?
"
default:
vegetableComment ="Everything tastes good in soup."
}
println(vegetableComment)
//_______________________________________________________________________________________________
//使用 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{
for number in numbers{
if number > largest{
largest = number
}
}
}
println("The largest number is(largest)")
//_______________________________________________________________________________________________
//使用 while /do while 语句
var n =2
whilen < 100{
n = n * 2
}
println("the n is(n)")
var m =2
do{
m = m * 2
}while m < 100
println("the m is(m)")
//_______________________________________________________________________________________________
//范围运算符
var firstForLoop =0
for iin 0..<4{ //使用 "..<"表示前闭后开范围
firstForLoop += i
}
println("firstForLoop is(firstForLoop)")
var secondForLoop =0
forvar i = 0; i <4; ++i{ //使用一般方法进行运算
secondForLoop += i
}
println("secondForLoop is(secondForLoop)")
var thirdForLoop =0
for iin 0...4{ //使用 "..."表示前闭后闭范围
thirdForLoop += i
}
println("thirdForLoop is(thirdForLoop)")
//***********************************************************************************************
//4.Function and Closures(函数和闭包)
//_______________________________________________________________________________________________
//函数的创建和使用
func greet(name: String, day: String) -> String{ //使用 "func 函数名(參数) -> 返回值类型{ return *** }" 来创建一个函数
return"Hello (name), today is (day)"
}
println(greet("Bob","Tusday"))
//_______________________________________________________________________________________________
//无參数的函数
func getGasPrices() -> (Double,Double, Double){ //函数參数为空
return (3.59,3.69, 3.79)
}
println(getGasPrices())
//_______________________________________________________________________________________________
//不确定參数的函数
func sumOf(numbers:Int...) -> Int{ //当函数參数不确定数量的时候,使用 "..."就可以
var sum = 0
for number in numbers{
sum += number
}
return sum
}
println(sumOf(234,34,12))
//_______________________________________________________________________________________________
//函数嵌套
func returnFifteen() ->Int{
var y = 10
func add(){
y +=5
}
add()
return y
}
println(returnFifteen())
//_______________________________________________________________________________________________
//函数作为返回值
func makeIncrementer() -> (Int ->Int){ //定义返回值为函数类型的函数 makeIncrementer
func addOne(number: Int) -> Int{
return 1 + number
}
return addOne
}
var increment =makeIncrementer()
println(increment(7))
//_______________________________________________________________________________________________
//函数做參数
func hasAnyMatches(list: [Int], condition:Int ->Bool) -> Bool{ //设置參数为整型数组和函数类型的函数 hasAnyMatches
for item in list{
if condition(item){
return true
}
}
return false
}
func lessThanTen(number:Int) -> Bool{ //定义函数符合 hasAnyMatches的參数类型
return number < 10
}
var numbers = [20,19, 7, 12]
println(hasAnyMatches(numbers,lessThanTen))
//_______________________________________________________________________________________________
//闭包
var numberArray = [3,45, 23, 523, 2]
let number =numberArray.map({ //Swift 中的 Array中有一个 map 方法。其获取的一个闭包表达式作为其唯一參数,数组中的每个元素调用次该闭包函数。并返回该元素所映射的值,详细的映射方式和返回值类型由闭包来指定
(number:Int) -> Int in
let result = 3 * number
return result
})
println(number)
//***********************************************************************************************
//5.Objects and Classes(对象和类)
//_______________________________________________________________________________________________
//类的创建
class Shape{ //使用 class声明一个类,类中的属性声明和声明常量变量一样。方法和函数声明是同样的方式
var numberOfSides = 0
func simpleDescription() -> String{
return"A shape with (numberOfSides) sides."
}
}
//_______________________________________________________________________________________________
//使用类
var shape = Shape() //实例化一个类。注意类名首字母大写
shape.numberOfSides =7 //设置类的属性
var shapeDescription =shape.simpleDescription() //訪问类的方法
println(shapeDescription)
//_______________________________________________________________________________________________
//使用 init 创建一个类的初始化器
class NamedShape{
var numberOfSides: Int = 0
var name: String
init(name: String){
self.name = name //self 用来区分属性和參数,在初始化这个类时,每一个初始值必须设置
}
func simpleDescription() -> String{
return"(name) find A shape with(numberOfSides) sides."
}
}
var name = NamedShape(name: "Listo") //实例化而且初始化类 NameShape
name.numberOfSides =7
var nameDescription =name.simpleDescription()
println(nameDescription)
//_______________________________________________________________________________________________
//继承和覆写
class Square:NamedShape{
var sideLength: Double
init(sideLength: Double, name:String){
self.sideLength = sideLength
super.init(name: name)
numberOfSides =4
}
func area() -> Double{
returnsideLength * sideLength
}
override func simpleDescription() ->String { //使用 override来覆写父类中的方法
return"A square with sides of length (sideLength)"
}
}
let test =Square(sideLength: 5.2, name: "my test square")
println(test.area())
println(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 //get 为获取这个属性的值
}
set{
sideLength = newValue / 3.0 //newValue 代表 set给这个属性的新的值
}
}
override func simpleDescription() ->String {
return"An equilateral triangle with side of length (sideLength)"
}
}
var triangle =EquilateralTriangle(sideLength: 3.1, name: "a triangle")
println(triangle.perimeter)
triangle.perimeter =9.9
println(triangle.sideLength)
//_______________________________________________________________________________________________
//类中的方法和函数的差别
class Counter{
var count: Int =0
func incrementBy(amount: Int, numberOfTimes times: Int){
count += amount * times
}
}
var counter =Counter()
counter.incrementBy(2, numberOfTimes: 7) //类中的方法须要在调用的时候写出參数的形參名(第一个參数名不能够写),函数在调用的时候除了外部參数存在的情况,否则不能參数的形參名
//***********************************************************************************************
//6.Enumeration and Structures(枚举和结构体)
//_______________________________________________________________________________________________
//枚举的创建
enum Rank: Int{ //使用 enum 创建一个枚举,注意枚举名用大写
case Ace =1 //指定第一个原始值为 1,后面的数据一次递增分配
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String{
switchself{ //这里的 self 就是一个枚举类型的值(enum value)
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
returnString(self.toRaw()) //使用 toRaw 和 fromRaw 来实现原始值和枚举值的转换
}
}
}
let ace =Rank.Ace
println(ace.simpleDescription())
let aceRawValue =ace.toRaw()
println(aceRawValue)
iflet convertedRank = Rank.fromRaw(3){
let threeDescription = convertedRank.simpleDescription()
println(threeDescription)
}
//_______________________________________________________________________________________________
//枚举成员是实际的值,不是其原始值的第二种表达方式
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 heartDescription =hearts.simpleDescription()
println(heartDescription)
//_______________________________________________________________________________________________
//结构体的创建(结构体和类之间最重要的一个差别是,结构体通过复制传递。类通过引用传递)
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()
println(threeOfSpadesDescription)
//_______________________________________________________________________________________________
//枚举的应用
enum ServerResponse{
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am","8:09 pm")
let failure = ServerResponse.Error("Out of cheese")
var serverResonse:String
switch success{
caselet .Result(sunrise, sunset):
serverResonse ="Sunrise is at (sunrise) and sunset is at(sunset)"
caselet .Error(error):
serverResonse = "Failure...(error)"
}
println(serverResonse)
//***********************************************************************************************
//7.Protocols and Extensions(协议和扩展)
//_______________________________________________________________________________________________
//协议的创建
protocol ExamplePortocol{ //使用 protocol 创建协议,协议名要大写
var simpleDescription: String { get}
mutating func adjust()
}
//_______________________________________________________________________________________________
//类,枚举,结构体都能够写协议
class SimpleClass:ExamplePortocol{ //类遵守协议。必须实现协议中的方法
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust(){ //在类中书写协议方法是不须要加上 mutating,由于一个类的方法能够改动类
simpleDescription +=" Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription =a.simpleDescription
println(aDescription)
struct SimpleStructure:ExamplePortocol{ //结构体遵守协议。必须实现协议中的方法
var simpleDescription: String = "A simple structure"
mutating func adjust() { //在结构体中书写协议方法时要记得加上 mutating
simpleDescription +=" (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
println(b.simpleDescription)
//_______________________________________________________________________________________________
//使用 extension将扩展功能加入到现有的类型中
extensionInt: ExamplePortocol{ //为协议加入功能
var simpleDescription: String{
return"The number (self)"
}
mutating func adjust(){
self += 42
}
}
//_______________________________________________________________________________________________
//使用协议作为数据类型
let protocolValue:ExamplePortocol = a
println(protocolValue.simpleDescription)
//***********************************************************************************************
//8.Generics(通用数据类型)
//_______________________________________________________________________________________________
//尖括号内写一个名字做一个通用的函数或类型
func repeat<ItemType>(item:ItemType, times: Int) -> [ItemType] { //做通用的类型
var result = [ItemType]()
for i in 0..<times{
result += item
}
return result
}
println(repeat("Knock",4))
//_______________________________________________________________________________________________
//你能够通用形式的函数和方法,以及类、枚举、结构
enum OptionalValue<T>{
case None
case some(T)
}
var possibleInteger:OptionalValue<Int> = .None
possibleInteger = .some(100)
println(possibleInteger)