swift学习记录

// Playground - noun: a place where people can play



import Cocoa



var myVariable=42

myVariable=50

let myConstant=42



let implicitInteger=70

let implicitDouble=70.0

let explicitDouble:Double=70



let explicitFloat:Float=4





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) piece of fruit"



let floatNumber:Float=4

let name="Ting"

let floatsummary="i am adding \(floatNumber+explicitFloat), haha \(name)"



var array=["catfish","water","tulips","blue paint"]

array[1]

array[1]="bottle of water"

var occupations = [

    "malcolm":"Captain",

    "Kaylee":"Mechanic",

]



occupations["Jayne"]="Public Relations"

occupations



let emptyArrary=String[]()

let emptyDictionary = Dictionary<String,Float>()



let shoppinglist=[]



let individualScores=[75,43,103,87,12]

var teamScore = 0

teamScore

for score in individualScores{

   "aaa"

    println(score)

}



"aaa"



for score in individualScores{

    if score > 50 {

        teamScore+=3

    } else {

        teamScore+=1

    }

    

}

teamScore



var optionalString:String? = "Hello"

optionalString == nil



var optionalName:String? = "John Appleseed"



var greeting = "Hello!"

if let name = optionalName{

    greeting = "Hello, \(name)"

} else if optionalName == nil {



    greeting = "Hello, nil"

}



let vegetable = "red pepper"

switch vegetable{

case "celery":

    let vegetableComment="Add some raisins and make ants on a log"

case "cucumber","watercress":

    let vegetableComment="That would make a good tea sandwich"

case let x where x.hasSuffix("pepper"):

    let vegetableComment="Is it a spicy \(x)?"

default:

    let vegetableComment="Everything tastes good in soup."

}



let interenstingNumber=[

    "prime":[2,3,5,7,11,13],

    "Fibonacci":[1,1,2,3,5,8],

    "Square":[1,4,9,16,25],

]



var largest = 0

var largestKind=""

for ( kind,numbers ) in interenstingNumber{

    for number in numbers {

        if number > largest{

        largest=number

        largestKind=kind

        }

    }

}

largest

largestKind



var n=2

while n < 100 {

n=n*2

}

n



var m=2

do{

m=m*2

}while m < 100

m



var firstLoop = 0

for i in 0..3 {

    firstLoop += i

}

firstLoop  //noticed 0..3 is 0, 1, 2 but not include 3, like python



var secondLoop = 0

for var i=0; i<3; i++ {

    secondLoop += i

}

secondLoop



var thirdLoop = 0

for i in 0...3 {

    thirdLoop += i

}

thirdLoop  //noticed 0..3 is 0, 1, 2 but not include 3, like python



func greet(name:String,lunch:String) ->String{

return "Hello \(name). Today's lunch is special \(lunch)!!!"

}



greet("Bob","Beef")



func getGasPrices()->(Double,Double,Double){

    return (3.49,3.59,3.69)

}



getGasPrices()



func sumOf(numbers: Int...) -> Int{

    var sum = 0

    for number in numbers {

        sum += number

    }

    return sum

}



sumOf()

sumOf(42,597,12)



5/2.0



func averageOf(numbers: Double...) ->Double{

    var average:Double = 0

    var sum:Double = 0

    numbers

    for number in numbers {

        sum += number

    }

    sum

    //var count:Double=numbers.count

    numbers.count == 3

    average = sum / 3

    var x:Double = Double(numbers.count)

    x

    sum

    651.0/3

    sum / x

    return average

    

}





averageOf(42,597,11)

651.0/3



func returnFifteen() -> Int{

    var y=10

    func add(){

        y += 5

        

    }

    y

    add()

    return y

}



returnFifteen()



func makeIncrementer() -> (Int -> Int){

    func addOne(number:Int)->Int{

    return 1 + number

    }

    return addOne

}

var increment=makeIncrementer()

increment(7)





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(numbers,lessThanTen)



numbers.map({

    (number:Int)-> Int in

    let result = 3 * number

    return result

    

    }

)



numbers.map({

    (number: Int)->Int in

    var result = 0

    if number % 2 == 1

    {

        result = 0

    }else {

     result = 3 * number

    }

    return result

    

    })



let x = numbers.map({number in 3 * number})

x



let bb=sort([1,5,3,12,2]){$0 > $1}

bb

let a = "hello"



"hello"



"aaa"



class Shape{

    let num=0

    var numberOfSides = 0

    func simpleDescription() -> String{

        return "A shape with \(numberOfSides) sides."

    }

    func simpleDescription2() -> String{



        return "A shape with \(num) sides."

   }

}

Shape().num

Shape().numberOfSides



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



    }



}



 



 



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



 



 



 



 



class Circle:NamedShape{



    



    var radius:Double



    



    init(radius:Double,name:String){



        self.radius = radius



        super.init(name: name)



    }



    func area()->Double



    {



        return 3.14 * radius * radius



    }



    



    override func simpleDescription() -> String {



        



        return "A Circle with radius=\(radius)."



    }



    



    



}



var circle = Circle(radius: 3, name: "smallCircle")



circle.area()



circle.simpleDescription()



 



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



    }



    }



    



    override func simpleDescription() -> String {



        return "An equilateral triagle with sides of length \(sideLength)."



    }



}



 



var triangle = EquilateralTriangle(sideLength:3.1,name:"a triangle")



triangle.perimeter



triangle.perimeter = 9.9



triangle.sideLength



 



class TriangleAndSquare{



    var triangle:EquilateralTriangle{



    willSet{



        square.sideLength = newValue.sideLength



    }



    }



    



    var square:Square{



    willSet{



        triangle.sideLength = newValue.sideLength



    }



    }



    



    init(size:Double, name:String){



        square = Square(sideLength:size, name:name)



        triangle = EquilateralTriangle(sideLength:size, name:name)



    }



    



}



var triangleAndSquare = TriangleAndSquare(size:10,name:"another test shape")



triangleAndSquare.square.sideLength



triangleAndSquare.triangle.sideLength



triangleAndSquare.triangle.perimeter = 90



triangleAndSquare.square.sideLength



triangleAndSquare.triangle.sideLength



 



triangleAndSquare.square = Square(sideLength:50, name:"larger square")



triangleAndSquare.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)



 



let optionalSquare: Square? = Square(sideLength:2.5, name:"optional square")



 



let sideLength = optionalSquare?.sideLength



 



 



 



 



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



        }



        



    }



}



let ace = Rank.Ace



let aceRawValue = ace.toRaw()



Rank.Ace.toRaw()



Rank.Ace.simpleDescription()



 



func compareRank(firstRank:Rank,secondRank:Rank) ->Int{



    



    var result:Int = firstRank.toRaw() - secondRank.toRaw()



    



    



    return result



}



 



 



let r = compareRank(Rank.Ace, Rank.Jack)



let x = r-1



let a = "hello"



let r2 = compareRank(Rank.Jack, Rank.Jack)



let r3 = compareRank(Rank.Jack, Rank.Six)



 



 



let a2 = "hello"



 



 



if let convertedRank = Rank.fromRaw(3){



    



    let threeDescription = convertedRank.simpleDescription()



}



 



 



 



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"



        }



    }



    func color() -> String{



        switch  self{



        case .Spades:



            return "black"



        case .Hearts:



            return "red"



        case .Diamonds:



            return "red"



        case .Clubs:



            return "black"



        }



        



    }



    



}



 



let hearts = Suit.Hearts



let heartsDescription  = hearts.simpleDescription()



 



Suit.Hearts.color()



Suit.Hearts.simpleDescription()



Suit.Clubs.color()



 



 



 



 



 



struct Card{



    var rank:Rank



    var suit:Suit



    func simpleDescription()->String{



        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"



    }



    



    func getDeck(){    // how ???



        



    }



    



}



 



let threeOfSpades = Card(rank: .Three, suit:.Spades)



threeOfSpades.simpleDescription()



 



threeOfSpades.getDeck()



 



 



 



enum ServerResponse {



    case Result(String,String)



    case Error(String)



    case myThree(String)



}



 



var success = ServerResponse.Result("6:00 am", "8:09 pm")



let failure = ServerResponse.Error("Out of cheese.")



success = ServerResponse.myThree("hahaha")



 



switch success{



case let .Result(sunrise, sunset):



    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."



case let .Error(error):



    let serverResponse = "Failure... \(error)"



case let .myThree(message):



    let serverResponse = "Welcome \(message)"



    



}



 



protocol ExampleProtocol{



    var simpleDescription: String {get}



    mutating func adjust()



}



 



 



class SimpleClass:ExampleProtocol{



    var simpleDescription: String  = "A very simple class."



    var anotherProperty: Int = 69105



    func adjust() {



        simpleDescription += "Now 100% adjusted."



    }



}



var ax = SimpleClass()



ax.adjust()



let aDescription =  ax.simpleDescription



 



struct SimpleStructure: ExampleProtocol{



    var simpleDescription:String="A simple structure"



    mutating func adjust(){



        simpleDescription += " (adjusted)"



    }



 



}



 



 



var bx = SimpleStructure()



bx.adjust()



let bDescription = bx.simpleDescription



"hello"



"aaa"



 



 



 



 



 



 



extension Int: ExampleProtocol{



    var simpleDescription:String{



    return "The number \(self)"



    }



    mutating func adjust(){



        self += 42



    }



 



}



 



7.simpleDescription



 



7.simpleDescription



 



 



let protocolValue:ExampleProtocol = ax



protocolValue.simpleDescription



//protocolValue.anotherProperty



 



func repeat<ItemType>(item:ItemType,times:Int)->ItemType[]{



    var result = ItemType[]()



    for i in 0..times{



        result += item



    }



    return result



}



 



repeat("knock", 4)



 



enum OptionalValue<T>{



    case None



    case Some(T)



}



var possibleInteger: OptionalValue<Int> = .None



possibleInteger = .Some(100)



 



 



 



func anyCommonElements < T,U where T:Sequence, U:Sequence, T.GeneratorType.Element:Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs:T,rhs:U) ->1[]{



    for lhsItem in lhs



    {



        for rhsItem in rhs{



            if lhsItem == rhsItem{



            



            }



        



        }



    



    }



    return false



}



"hello"



anyCommonElements([1,2,3], [3])

let orangesAreOrange = true//自动推断为bool

let turnipsAreDelicious = false



if turnipAreDelicious{

    println("Mmm,tasty turnips!")

} else {

    println("Eww, turnips are horrible.")

}



let i = 1

if i{

//if语句不能用非bool值

}



if i==1{

//这样就可以

}



//5.元组tuple

let http404Error = (404,"Not Found")

let (statusCode,StatusMessage)= http404Error

println("The status code is \(statusCode)")

println("The status message is \(statusMessage)")



let (justTheStatusCode,_) = http404Error

println("The status code is \(justTheStatusCode)")



println("The status code is \(http404Error.0)")

println("The status message is \(http404Error.1)")



//tuple里的别名

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

println("The status code is \(http200Status.statusCode)")

println("The status message is\(http200Status.description)")





//Optional:有值或者不存在。这个地方看起来,java里很多的nullPointerException在swfit里可以避免了。

//也就是说我不用try catch

let possibleNumber = "123"

let convertedNumber = possibleNumber.toInt()   //这个变量的类型推断结果是 Int? 或者optional Int



//用if来判断optional是否有值

if convertedNumber{

    println("\(possibleNumber) has an Integer value of \(convertedNumber!)")

}else{

    println(("\possibleNumber") could not be converted to an integer)

}





if let actualNumber = possibleNumber.toInt(){

    println("\(possibleNumber) has an Integer value of \(actualNumber!)")

}

else{

    println(("\possibleNumber") could not be converted to an integer)

}



//optional变量的初始化

var serverResponseCode:Int? = 404 //值为404

serverResponseCode = nil  //空值



var surveyAnswer:String?//自动nil



let possibleString: String? = "An optional string"

println(possibleString!)



let assumedString: String! = "An implicitly unwrapped optional string."

println(assumedString)



if assumedString{

    println(assumedString)

}



if let definiteString = assumedString {

    println(definiteString)

}





let age = -3

assert(age >= 0, "A person's age cannot be less than zero")



assert(age >= 0)





let b = 10

var a =5

a = b





let (x,y) = (1,2)



if x = y {

//invalid, no return value

}



1+2

5-3

2*3

10.0/2.5 //=4.0 



"hello,"+"world"

let dog:Character = "dog"

let cow:Character = "cow"

let dogCow = dog + cow//="dogcow"

let num = 5

//let combine = dog + num // 报错

let combine = dog + String(num)



9%4//=1

-9%4//=-1

8%2.5//0.5



var i = 0

++i



var a = 0

let b = ++a//a=1,b=1

let c = a++//a=2,c=1



let three = 3

let minusThree = -three

let plusThree = -minusThree



let minusSix = -6

let alsoMinusSix = +minusSix//=-6



var a = 1

a += 2



let name = "world"

if name == "world" {

    println("hello,world")

} else {

    println("I'm sorry \(name), but I don't recognize you")

}



let contentHeight = 40

let hasHeader = true

let rowHeight = contentHeight +(hasHeader ? 50 : 20)





//6.Range

//1到5,包括1也包括5

for index in 1...5{

    println ("\(index) times 5 is \(index * 5)")

}



let names = ["Anna","Alex.","Brian","Jack"]

let count = names.count

//0到count,包括0不包括count,所以其实是0到count-1

for i in 0..count{

    println("Person \(i+1)" is called \(names[i]))

}



let allowedEntry = false

if !allowedEntry{

    println("ACCESS DENIED")

}



let enteredDoorCode = true

let passedRetinaScan = false

if enteredDoorCode && passedRetinaScan{

    println("Welcome!")

} else {

    println("ACCESS DENIED")

}



if (enteredDoor && passedRetinaScan) || hasDoorKey || knowsOveridePassword{

    println("Welcome!")

} else {

    println("ACCESS DENIED")

}



let someString = "Some string literal value"



let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"

let dollorSign = "\x24"

let blackHeart = "\u2665"

let sparkingHeart = "\U0001F496"



var emptyString = ""

var anotherEmptyString = String()



if emptyString.isEmpty {

    println("Nothing to see here")

}





var variableString = "Horse"

variableString += " and carriage"



let constantString = "highlander"

constantString += " and another Highlander" // compile-time error



for character in "Dog!"{

    println(character)

}





let yenSign:Character = "¥" //need the type annotation or it will be a string



let unusualMenagerie = "Koala , Snail ,Penguin ,Dromedary "

println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")



let string1 = "hello"

let string2 = " there"

let character1:Character = "!"

let character2:Character = "?"



let stringPlusCharacter = string1 + character1

let stringPlusString = string1 + string2

let characterPlusString = character1 + string1

let characterPlusCharacter = character1 + character2



var instruction = "look over"

instruction += string2



var welcome = "good morning"

welcome += character1



let multiplier = 3

let message = "\(multiplier) times 2.5 is \(Double(multiplier)*2.5)"



let quotation = "We're a lot alike, you and I."

let sameQuotation = "We're a lot alike, you and I."

if quotation == sameQuotation{

    println("These two strings are considered equal")

}





let romeoAndJuliet = [

    "Act 1 Scene 1: Verona, A public place",

    "Act 1 Scene 2: Capulet's mansion",

    "Act 1 Scene 3: A room in Capulet's mansion",

    "Act 1 Scene 4: A street outside Capulet's mansion",

    "Act 1 Scene 5: The Great Hall in Capulet's mansion",

    "Act 2 Scene 1: Outside Capulet's mansion",

    "Act 2 Scene 2: Capulet's orchard",

    "Act 2 Scene 3: Outside Friar Lawrence's cell",

    "Act 2 Scene 4: A street in Verona",

    "Act 2 Scene 5: Capulet's mansion",

    "Act 2 Scene 6: Friar Lawrence's cell"

]



var act1SceneCount = 0

for scene in romeoAndJuliet{

    if scene.hasPrefix("Act 1"){

        ++act1SceneCount

    }

}

println("There are \(act1SceneCount) scenes in Act 1")



var mansionCount = 0

var cellCount = 0

for scene in romeoAndJuliet{

    if scene.hasSuffix("Capulet's mansion"){

        ++mansionCount

    } else if scene.hasSuffix("Friar Lawrence's cell"){

        ++cellCount

    }

}

println("\(mansionCount) mansion scenes;\(cellCount) cell scenes")



let normal = "Could you help me,please?"

let shouty = normal.uppercaseString

let whispered = normal.lowercaseString



let dogString = "Dog!"

for codeUnit in dogString.utf8{

print("\(codeUnit)")

}

print("\n")



for codeUnit in dogString.utf16{

print("\(codeUnit)")

}

print("\n")



for scalar in dogString.unicodeScalars{

    print("\(scalar.value)")

}

print("\n")



var shoppingList:String[]=["Eggs","Milk"] //var所以可以再加元素,let就不行了



var shoppingList = ["Eggs","Milk"] //因为类型推断,一个array必须包含同类元素,所以能推断出来是string类



println("The shopping list contains \(shoppingList.count) items.")



if shoppingList.isEmpty{

    println("The shopping list is empty.")

} else {

    println("The shopping list is not empty.")

}



shoppingList.append("Flour")

shoppingList += "Baking Powder"

shoppingList += ["Chocolate Spread","Cheese","Butter"]



var firstItem = shoppingList[0]



shoppingList[0] = "Six eggs"

shoppingList[4...6]=["Bananas","Apples"] //4...6有3个元素,所以3个元素被换成了2个。不能越界哦。

shoppingList.insert("Maple Syrup",atIndex:0)



let mapleSyrup = shoppingList.removeAtIndex(0)//删除并放到mapSyrup里,而且所有元素都往前移了一格

firstItem = shoppingList[0]



let apples = shoppingList.removeLast()//删除并赋值,减少了array长度



for item in shoppingList{  //遍历

    println(item)

}



for (index,value) in enumerate(shoppingList){

    println("Item \(index + 1):\(value)")

}

    //Item 1:Six eggs

    //Item 2:Milk

    //...

    

var someInts = Int[]()   //var someInts:Int[] = [1,2,3]   var someInts = [1,2,3] 

println("someInts is of type Int[] with \(someInts.count) items.")



someInts.append(3)

someInts = []



var threeDoubles = Double[](count:3,repeatedValue:0.0)

var anotherThreeDoubles = Array(count:3,repeatedValue:2.5)//inferred as Double[]



var sixDoubles = threeDoubles + anotherThreeDoubles



var airports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"]

var airports = ["TYO":"Tokyo","DUB":"Dublin"]

println("The dictionary of airports contains \(airports.count) items.")

airports["LHR"] = "London"



airports["LHR"] = "London Heathrow"



if let oldValue = aiports.updateValue("Dublin International", forKey:"DUB"){

    println("The old value for DUB was \(oldValue).")

}



if let airportName = airports["DUB"]{

    println("The name of the airport is \(airportName).")

} else {

    println("That airport is not in the airports dictionary")

}



airports["APL"] = "Apple International"

airports["APL"] = nil //从字典里删元素



if let removedValue = airports.removeValueForKey("DUB"){

    println("The removed airport's name is \(removedValue).")

} else {

    println("The airports dictionary does not contain a value for DUB.")

}



for(airportCode, airportName) in airports{

    println("\(airportCode):\(airportName)")

}



for airportCode in airports.keys{

    println("Airport code:\(airportCode)")

}



for airportName in airports.values{

    println("Airport name:\(airportName)")

}



let airportCodes = Arrary(airports.keys)

let airportNames = Arrary(airports.values)



//dictionary里元素没有顺序,所以遍历时顺序不确定和插入时顺序一致



var namesOfIntegers = Dictionary<Int,String>()//初始化一个空字典

namesOfIntegers[16]="sixteen"//可以类型推断出来

namesOfIntegers = [:]//再次置为空值,但类型不变





//let的immutable的dictionary不能改变key,一旦设定value后也不能改变key的对应value。arrary则可以改变value。都不能增加长度

//如果长度固定,尽量用let



for index 1...5{ //index隐式声明,不用let

    println("\(index) times 5 is \(index * 5)")

}



let base = 3

let power = 10

var answer = 1

for _ in 1...power{//如果元素无所谓,可以下划线代替

    answer *= base

}

println("\(base) to power of \(power) is \(answer)")



let names = ["Anna","Alex","Brian","Jack"]

for name in names{

    println("Hello,\(name)!")

}



let numberOfLegs = ["spider":8,"ant":6,"cat":4]

for (animalName,legCount) in numberOfLegs{

    println("\(animalName)s have \(legCount) legs")

}



for character in "Hello"{}

    println(character)

}



for var index = 0; index < 3; ++index{

    println("index is \(index)")

}



var index:Int

for index = 0; index <3; ++index{

    println("index is \(index)")

}

println("The loop statements were executed (\index) times")



let finalSquare = 25

var board = Int[](count: finalSquare + 1,repeatedValue:0)



board[03]=+08;board[06]=+11;board[09]=+09;board[10]=+02

board[14]=-10;board[19]=-11;board[22]=-02;board[24]=-08



var square = 0

var diceRoll = 0

while square < finalSquare{

    //roll the dice

    if ++diceRoll==7{diceRoll = 1}

    //move by the rolled amount

    square += diceRoll

    if square < board.count{

        square +=board[square]

    }

    

}



println("Game over!")





do{

square += board[square]



if ++diceRoll == 7 {diceRoll = 1}



square += diceRoll

} while square < finalSquare

println("Game over!")



var temperatureInFahrenheit = 30

if temperatureInFahrenheit <= 32{

    println("It's very cold. Consider wearing a scarf.")

}

//###############################################################################

temperatureInFahrenheit = 40

if temperatureInFahrenheit <= 32{

    println("It's very cold. Consider wearing a scarf.")

} else {

    println("it's not that cold. Wear a t-shit.")

} 



temperatureInFahrenheit = 90

if temperatureInFahrenheit <= 32{

    println("It's very cold. Consider wearing a scarf.")

}    else if temperatureInFahrenheit >= 86{

    println("It's really warm. Don't forget to wear sunscreen")

} else {

    println("it's not that cold. Wear a t-shit.")

} 



let someCaracter:Character = "e"

switch someCharacter{

case "a","e","i","o","u":

    println("\(someCharacter) is a vowel")

case "b","c":

    println("\(someCharacter)is a consonant")

default:

    println("\(someCharacter) is not a vowel or a consonant")

}



//switf 的switch语句的各个case之间没有顺序执行关系。跑完一个case之后会直接结束,而不是接着跑下一个case

//一般不用写break了。但想用的时候还是可以用break的。

//case后面必须至少包含一个可执行语句,否则会报错。

let anotherCharacter:Character = "a"

switch anotherCharacter{

case "a":

case "A":

    println("The letter A")

default:

    println("Not the letter A")

}

//那要多项匹配时就可以用逗号隔开

//Range匹配

let count = 3_000_000_000_000

let countedThings = "stars in the Milky Way"

var naturalCount:String

switch count {

case 0:

    naturalCount = "no"

case 1...3:

    naturalCount = "a few"

case 4...9:

    naturalCount = "several"

case 10...99:

    naturalCount = "tens of"

case 100...999:

    naturalCount = "hundreds of"

case 1000...999_999:

    naturalCount = "thousands of"

default:

    naturalCount = "millions and millions of"

}

println("There are \(naturalCount) \(countedThings)")



//tuple.0里的0是index下标

//如果同时匹配上了多个case,则第一个生效,其他忽略

let somePoint = (1,1)

switch somePoint{

case(0,0):

    println("(0,0) is at the origin")

case(_,0):

    prinltn("(\(somePoint.0),0) is on the x-axis")

case(0,_):

    println("(0,\(somePoint.1)) is on the y-axis)

case(-2...2,-2...2):

    println("(\(somePoint.0),\(somePoint.1)) is inside the box")

default:

    println("(\(somePoint.0),\(somePoint.1)) is outside of the box")

}





let anotherPoint = (2,0)

switch anotherPoint{

case(let x,0):

    println("on the x-axis with an x value of \(x)")

case (0,let y):

    println("on the y-axis with a y value of \(y)")

case let(x,y):

    println("somewhere else at (\(x),\(y))")

}



let yetAnotherPoint = (1,-1)

switch yetAnotherPoint{

case let(x,y) where x == y:

    println("(\(x),\(y)) is on the line x == y")

case let(x,y) where x == -y:

    println("(\(x),\(y)) is on the line x == -y")

case let(x,y):

    println("(\(x),\(y)) is just some arbitrary point")

}



let puzzleInput = "great minds think alike"

var puzzleOutput = ""

for character in puzzileInput {

    switch character{

    case "a","e","i","o","u"," ":

        continue

    default:

        puzzleOutput += character

    }

}

println(puzzleOutput)





//switch中可以用break来表示忽略一个case

let numberSymbol:Character = ""

var possibleIntegerValue:Int?

switch numberSymbol{

case "1", "١" ,"", "":

    possibleIntegerValue = 1

case "2", "٢" ,"", "":

    possibleIntegerValue = 2

case "3", "٣" ,"", "":

    possibleIntegerValue = 3

case "4", "٤" ,"", "":

    possibleIntegerValue = 4

default:

    break

}



if let integerValue = possibleIntegerValue{

    println("THe integer value of \(numberSymbol) is \(integerValue)")

} else {

    println("An integer value could not be found for \(numberSymbol)")

}



let integerToDescribe = 5

var description = "The number \(integerToDescribe) is"

switch integerToDescribe{

    description += "a prime number, and also"

    fallthrough

default:

    description += "an integer."

}

println(description)





let finalSquare = 25

var board = Int[](count: finalSquare + 1,repeatedValue:0)



board[03]=+08;board[06]=+11;board[09]=+09;board[10]=+02

board[14]=-10;board[19]=-11;board[22]=-02;board[24]=-08



var square = 0

var diceRoll = 0

gameLoop:while square!=finalSquare{

    if ++diceRoll == 7 {diceRoll = 1}

    switch square + diceRoll {

    case finalSquare:

        break gameLoop

    case let newSquare where newSquare>finalSquare:

        continue gameLoop

    default:

        square += diceRoll

        square += board[square]

    }

}

println("Game over!")



func sayHello(personName:String) -> String{

    let greeting = "Hello," + personName + "!"

    return greeting

}



println(sayHello("Anna"))

println(sayHello("Brian"))



func sayHelloAgain(personName:String) -> String{

    return "Hello again," + personName + "!"

}

println(sayHelloAgain("Anna"))



func halfOpenRangeLength(start:Int,end:Int) -> Int{

    return end - start

}

println(halfOpenRangeLength(1,10))



func sayHelloWorld() -> String{

    return "hello,world"

}

println(sayHelloWorld())



//其实返回了空tuple()

func sayGoodbye(personName:String){

    println("Goodbye,\(personName)!")

}

sayGoodbye("Dave")



func printAndCount(stringToPrint:String) -> Int{

    println(stringToPrint)

    return countElements(stringToPrint)

}

func printWithoutCounting(stringToPrint:String){

    printAndCount(stringToPrint)

}

printAndCount("hello,world")

printWithoutCount("Hello,world")



//func里用tuple返回多个值

func count(string:String) ->(vowels:Int,consonants:Int,others:Int){

    var vowels = 0, consonants = 0, others = 0

    for character in string{

        switch String(character).lowercaseString{

        case "a","e","i","o","u":

            ++vowels

        case "b","c",xxxxxxxxxxxxxxxx:

            ++consonants

        default:

            ++others

        }

    }

    return (vowels,consonants,others)

    

}



let total = count("some arbitrary string!")

println("\(total.vowels) vowels and \(total.consonants) consonants")



//patameterName是局部变量,只在func体内生效

func someFunction(parameterName:Int){

}

//如果定义了external paramter name,那调用时必须使用他

func someFunction(externalParameterName localParameterName:Int){

}



//不用external paramter name时,调用方法的时候看不出来每个参数是什么

func join(s1:String,s2:String,joiner:String) -> String{

    return s1 + joiner + s2

}

join("hello","world",",")

//用了external paramter name的话

func join(string s1:String, toString s2:String, withJoiner joiner:String) -> String{

    return s1 + joiner +s2

}

join(string:"hello",toString:"world",withJoiner:",")



//external parameter简写

func containsCharacter(#string:String,#characterToFind:Character) -> Bool{

    for character in string{

        if character == characterToFind{

            return true

        }

    }

    return false

}



let containsAVee = containsCharacter(string:"aardvark",characterToFind:"v")



//默认值

func join(string s1:String, toString s2:String, withJoiner joiner:String = "") ->{

    return s1 + joiner +s2

}

//如果有传值,就正常调用

join(string:"hello",toString:"world",withJoiner:"=")

//如果没有传,就用默认值了

join(string:"hello",toString:"world")



//如果有了默认值,就自动有了external parameter name

func join(s1:String, s2:String, joiner:String = " ")->String{

    return s1 + joiner + s2

}



join("hello","world",joiner:"-")



//variadic parameter加三个点.一个数组。每个方法最多一个可变参数,一定要放最后

func arithmeticMean(numbers:Double...)->Double{

    var total:Double = 0

    for number in numbers{

        total += number

    }

    return total / Double(numbers.count)

}



arithmeticMean(1,2,3,4,5) //3.0

arithmeticMean(3.8.19)//10.0





//constant and variable parameters

//默认都是constant。而variable参数是copy一个参数的值来用。可以改。

func alinRight(var string:String, count:Int, pad:Character) -> String{

let amountToPad = count- countElements(string)

for _ in 1...amountToPad{

    string = pad + string

}

return string

}

let originalString = "hello"

let paddedString = alignRight(originalString,10,"-")

//-----hello

//注意,这里,originalString值没改。



//inout 参数

//这个类型的参数跟上面这个不同,会影响original string

//inout不能是可变参数,

//inout 不能用var、let来标记,默认var

func swapTwoInts(inout a:Int, inout b:Int){

    let temporaryA = a

    a = b

    b = temporaryA

}





var someInt = 3

var anotherInt = 107

swapTwoInts(&someInt,&anotherInt)

//这里注意加了&符号,这样才能用于inout参数



func addTwoInts(a: Int, b: Int) -> Int{

    return a + b

}



func multiplyTwoInts(a: Int, b: Int) -> Int{

    return a * b

}



func printHelloWorld(){

    println("hello, world")

}



// (Int, Int) -> Int 是func的type,addTwoInts是一个func,这里把这个func赋值给一个var

var mathFunction: (Int, Int) -> Int = addTwoInts



println("Result: \(mathFunction(2,3))")//5



mathFunction = multiplyTwoInts



println("Result: \(mathFunction(2,3))")//6





let anotherMathFunction = addTwoInts //类型推断也可以适用



//func做参数

func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int){

    println("Result: \(mathFunction(a,b))")

}

printMathResult(addTwoInts, 3, 5)

printMathResult(multiTwoInts, 3, 5)



//func做返回值

func stepForward(input: Int) -> Int{

    return input + 1

}



func stepBackward(input: Int) -> Int{

    return input - 1

}



func chooseStepFunction(backwards: Bool) -> (Int) -> Int {

    return backwards ? stepBackward : stepForward

}



var currentValue = 3

let moveNearerToZero = chooseStepFunction(currentValue > 0)//然后moveNearerToZero就指向了stepBackward()了





println("Counting to zero:")

//Counting to zero:

while currentValue != 0 {

    println("\(currentValue)...")

    currentValue = moveNearerToZero(currentValue)

}

println("zero!")

//3...

//2...

//1...

//zero!





//nested func 

func chooseStepFunction(backwards: Bool) -> (Int) -> Int{

    func stepForward(input: Int) -> Int { return input + 1 }

    func stepBackward(input: Int) -> Int { return input - 1 }

    return backwards ? stepBackward : stepForward

}



var currentValue =  -4

let moveNearerToZero = chooseStepFunction(currentValue > 0)

//now it  refers to the nested stepForward() function



while currentValue != 0{

    println("\(currentValue)...")

    currentValue = moveNearerToZero(currentValue)

}

println("zero!")

//-4...

//-3...

//-2...

//-1...

//zero!





let names = ["Chris","Alex","Ewa","Barry","Daniella"]



func backwards(s1: String, s2: String) -> Bool {

    return s1 > s2

}



var reversed = sorted(names, backwards)



reversed = sorted( names, { (s1: String, s2: String) -> Bool in 

    return s1 > s2

})



reversed = sorted(names, {s1,s2 in return s1 > s2})



reversed = sorted(names, {s1, s2 in s1 > s2})



reversed = sorted(names, {$0 > $1})



reversed = sorted(names, >)



func someFunctionThatTakesAClosure(closure: () -> ()){

//xxxxxxxxxxxxxxxxx

}



//普通调用

someFunctionThatTakesAClosure({

//xxxx

})

//trailing closure调用

someFunctionThatTakesAClosure(){

//xxxx

}



reversed = sorted(names){$0 > $1}





let digitNames = [0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 

                  5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine",

]



let numbers = [16,58,150]





let strings = numbers.map {

    (var number) -> String in

    var output = ""

    while number > 0 {

        output = digitNames[number % 10]! + output

        number /= 10

    }

    return output

}



func makeIncrementor(forIncrement amount: Int) -> () -> Int{

    var runningTotal = 0

    func incrementor() -> Int{

        runningTotal += amount

        return runningTotal

    }

    return incrementor

}



let incrementByTen = makeIncrementor(forIncrement: 10)

incrementByTen()// 10

incrementByTen()// 20



let incrementBySeven = makeIncrementor(forIncrement: 7)

incrementBySeven()//7

incrementByTen()// 30



let alsoIncrementByTen = incrementByTen

alsoIncrementByTen()//40





enum SomeEnumeration {

    //enumeration definition here

}



enum CompassPoint {

    case North

    case South

    case East

    case West

}



enum Planet {

    case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune

}



var directionToHead = CompassPoint.West



directionToHead = .East



directionToHead = .South



switch directionToHead {

    case .North:

        println("Lots of planet have a north")

    case .South:

        println("Watch out for penguins")

    case .East:

        println("Where the sun rises")

    case .West:

        println("Where the skies are blue")

}



let somePlanet = Planet.Earth

switch somePlanet {

    case .Earth:

        println("Mostly harmless")

    default:

        println("Not a safe place for humans")

}



enum Barcode{

    case UPCA(Int, Int, Int, Int)

    case QRCode(String)

}



var productBarcode = Barcode.UPCA(8,85909,51226,3)



productBarcode = .QRCode("ABCDEFGHIJKLMNOP")



switch productBarcode {

case .UPCA(let numberSystem, let manufacturer, let product, let check):

    println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")

case .QRCode(let productCode):

    println("QR code: \(productCode).")

}



switch productBarcode {

case let .UPCA( numberSystem, manufacturer, product, check):

    println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")

case let .QRCode(productCode):

    println("QR code: \(productCode).")

}





enum ASIIControlCharacter: Character{

    case Tab = "\t"

    case LineFeed = "\n"

    case CarriageReturn = "\r"

}



//raw values 一直不变,associated values 只指定了类型







enum Planet: Int{

    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune

}



let earthsOrder =  Planet.Earth.toRaw()

let possiblePlanet = Planet.fromRaw(7)



//根据类型推断,possiblePlanet是一个optional planet即 Planet?类型

//也就是说 let possiblePlanet: Planet? = Planet.fromRaw(7)



let positionToFind = 9

if let somePlanet = Planet.fromRaw(positionToFind) {

    switch somePlanet{

    case .Earth:

        println("Mostly harmless")

    default:

        println("Not a safe place for humans")

        }

} else {

    println("There isn't a planet at position \(positionToFind)")

} 



class SomeClass{



}



struct SomeStructure{



}



struct Resolution{

    var witdth = 0

    var height = 0

}



class VideoMode{

    var resolution = Resolution()

    var interlaced = false

    var frameRate = 0.0

    var name: String?

}



let someResolution = Resolution()

let someVideoMode = VideoMode()



println("The width of some Resolution is \(someResolution.width)")

println("The width of someVideoMode is \(someVideoMode.resolution.width)")



someVideoMode.resolution.width = 1280

println("The width of someVideoMode is now \(someVideoMode.resolution.width)")



let vga = Resolution(width: 640, height: 480)



let hd = Resolution(width: 1920, height: 1080)

var cinema = hd



cinema.width = 2048

println("cinema is now \(cinema.width) pixels wide")

//prints "cinema is now 2048 pixels wide"



println("hd is still \(hd.width) pixels wide")

//prints "hd is still 1920 pixels wide"



enum CompassPoint{

    case North, South, East, West

}

var currentDirection = CompassPoint.West

let rememberedDirection = currentDirection

currentDirection =.East

if rememberedDirection == .West{

    println("The remembered Direction is still .West")

}



let tenEighty = VideoMode()

tenEighty.resolution = hd

tenEighty.interlaced = true

tenEighty.name = "1080i"

tenEighty.frameRate = 25.0



let alsoTenEighty = tenEighty

alsoTenEighty.frameRate = 30.0



ptintln("The frameRate property of tenEighty is now \(tenEighty.frameRate)")

//class 按引用传递,所以等于是设置了个别名一样的。



if tenEighty ===alsoTenEighty {

    println("tenEighty and alsoTenEighty refer to the same VideoMode instance")

}



struct FixedLengthRange {

    var firstValue: Int

    let length: Int

}

var rangeOfThreeItems = FixedLengthRange(firstValue:0,length:3) //0,1,2

rangeOfThreeItems.firstValue = 6//6,7,8



let rangeOfFourItems = FixedLengthRange(firstValue: 0,length: 4)

rangeOfFourItems.firstValue = 6





//struct 按值传递,所以struct是constant时,struct的property也是constant无法改变

//class 按引用传递,即使class是constant,property仍可以改变



class DataImporter{

/*

DataImporter is a class to import data from an external file. The class is assumed to take a non-travel amount of time to initialize

*/

var fileName = "data.txt"

//the DataImporter class would provide data importing functionality here

}



class DataManager{

lazy var importer = DataImporter()

var data = [String]()

//The dataManager class would provide  data management functionality here

}



let manager = DataManager()

manager.data.append("Some data")

manager.data.append("Some more data")

//the DataImporter instance for the importer property has not yet been created 所以是lazy发挥了作用



println(manager.importer.fileName)

//the data importer instance for the importer property has now been created



struct Point{

    var x = 0.0, y = 0.0

}

struct Size {

    var width = 0.0, height = 0.0

}

struct Rect {

    var origin = Point()

    var size = Size()

    var center: Point{

        get{

            let centerX = origin.x + (size.width / 2)

            let centerY = origin.y + (size.height / 2)

            return Point (x: centerX, y:centerY)

        }

        set(newCenter){

            origin.x = newCenter.x - (size.width / 2)

            origin.y = newCenter.y - (size.height / 2)

        }

    }

}



var square = Rect(origin: Point(x: 0.0, y: 0.0),

    size: Size(width:10.0, height: 10.0))

let initialSquareCenter = square.center

square.center = Point(x:15.0, y:15.0)

println("square.origin is now at (\(square.origin.x), \(square.origin.y))")



struct AlternativeRect{

    var origin = Point()

    var size = Size()

    var center: Point{

        get{

            let centerX = origin.x + (size.width / 2)

            let centerY = origin.y + (size.height / 2)

            return Point(x: centerX, y: centerY)

        }

        set{

            origin.x = newValue.x - (size.width / 2)

            origin.y = newValue.y - (size.height / 2)//newValue is the default name in setter

        }

    }

}





struct Cuboid {

    var width = 0.0, height = 0.0, depth = 0.0

    var volume: Double{

        return width * height * depth

    }

}



let fourByFiveByTwo = Cuboid(width: 4.0, height:5.0, depth:2.0)

println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") //40.0



class StepCounter {

    var totalSteps: Int = 0

        willSet(newTotalSteps){

            println("About to set totalSteps to \(newTotalSteps)")

        }

        didSet{

            if totalSteps > oldValue {

                println("Added \(totalSteps - oldValue) steps")

            }

        }

}

let stepCounter = stepCounter()

stepCounter.totalSteps = 200

//About to set totalSteps to 200

//Added 200 steps

stepCounter.totalSteps = 360

//About to set totalSteps to 360

//Added 160 steps

stepCounter.totalSteps = 896

//About to set totalSteps to 896

//Added 536 steps







//Type property syntax

struct SomeStructure{

    static var storedTypeProperty = "Some value."

    static var computedTypeProperty: Int{

    // return an Int value here

    }

}

//Type property syntax

enum SomeEnumeration {

    static var storedTypeProperty = "Some Value"

    static var computedTypeProperty: Int{

        //return an Int value here

    }

}

//Type property syntax

class SomeClass{

    class var computedTypeProperty: Int{

    //return an Int value here

    }

}



println(SomeClass.computedTypeProperty)//prints "42"

println(SomeStructure.storedTypeProperty)//prints "Some value"

SomeStructure.storedTypeProperty = "Another value."

println(SomeStructure.storedTypeProperty)//prints "Another value."



struct AudioChannel {

    static let thresholdLevel = 10

    static var MaxInputLevelForAllChannels = 0

    var currentLevel: Int = 0

        didSet{

            if currentLevel > AudioChannel.thresholdLevel{

            // cap the new audio level to the threshold level

            currentLevel = AudioChannel.thresholdLevel//这个操作不会再次call didSet

            }

            if currentLevel > AudioChannel.maxInputLevelForAllChannels{

            //store this as the new overall maximum input level

            AudioChannel.maxInputLevelForAllChannels = currentLevel

            }

        }

}



var leftChannel = AudioChannel()

var rightChannel = AudioChannel()



leftChannel.currentLevel = 7

println(leftChannel.currentLevel)

println(AudioChannel.maxInputLevelForAllChannels)



rightChannel.currentLevel = 11

println(rightChannel.currentLevel)

println(AudioChannel.maxInputLevelForAllChannels)



class Counter{

    var count = 0

    func increment() {

        count++

    }

    func incrementBy(amount: Int){

        count += amount

    }

    func reset(){

        count = 0

    }

    

}



let count = Counter()

counter.increment()

counter.incrementBy(5)

counter.reset()

class Counter{

    var count = 0

    func incrementBy(amount: Int, numerOfTimes: Int){

        count += amount * numberOfTimes

    }

}



let counter = Counter()

counter.incrementBy(5, numberOfTimes: 3)



func incrementBy(amount: Int, #numberOfTimes: Int){

    count += amount * numberOfTimes

}



func increment(){

    self.count++

}



struct Point{

    var x = 0.0, y = 0.0

    func isToTheRightOfX(x: Double) -> Bool{

        return self.x > x

    }

}



let somePoint = Point(x: 4.0, y: 5.0)

if somePoint.isToTheRightOfX(1.0){

    println("This point is to the right of the line where x == 1.0")

}



struct Point {

    var x = 0.0, y = 0.0

    mutating func moveByX(deltaX: Double, y deltaY: Double){

        x += deltaX

        y += deltaY

    }

}

var somePoint = Point(x: 1.0, y: 1.0)

somePoint.moveByX(2.0, y: 3.0)



struct Point{

    var x = 0.0, y = 0.0

    mutating func moveByX(deltaX: Double, y deltaY: Double){

        self = Point(x: x + deltaX, y: y + deltaY)

    }

}



enum TriStateSwitch {

    case Off, Low, High

    mutating func next(){

        switch self{

        case Off:

            self = Low

        case Low:

            self = High

        case High:

            self = Off

        }

    }

}



var ovenLight = TriStateSwitch.Low

ovenLight.next() //High

ovenLight.next()  //Off



class SomeClass {

    class func someTypeMethod() {

    // implementation

    }

}

SomeClass.someTypeMethod()



struct LevelTracker{

    static var highestUnlockedLevel = 1

    static func unlockLevel(level: Int){

        if level > highestUnlockedLevel{

            highestUnlockedLevel = level

        }

    }

    static func levelIsUnlocked(level: Int) -> Bool{

        return level <= highestUnlockedLevel

    }

    var currentLevel = 1

    mutating func advanceToLevel(level: Int) -> Bool{

    if LevelTracker.levelIsUnlocaked(level){

        currentLevel = level

        return true

    }    else {

        return false

    }

    

    }

    

}



class Player{

    var tracker = LevelTracker()

    let playerName: String

    func completedLevel(level: Int){

        LevelTracker.unlockLevel(level + 1)

        tracker.advanceToLevel(level + 1)

    }

    init(name: String){

        playerName = name

    }

}



var player = Player(name: "Argyrios")

player.completedLevel(1)

pritnln("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")



player = Player(name: Beto)

if player.tracker.advanceToLevel(6){

    println("player is now on level 6")

}  else {

    println("level 6 has not yet been unlocked")

}
View Code

 

 

0.句末不用打分号

1.变量var 常量let,不用指定类型,自动推断

2.当需要指定类型时:

let explicitDouble:Double=7  //7.0

3.+号不能自动把数字变成string,全部用显式转换:

let label="The width is"



let width=94



let widthLable= label+String(width) 

4.也可以用\()来插入一个变量或常量,比java麻烦嘛。

let apples=3

let summary="I have \(apple) apples" // I have 3 apples

let oranges=5

let fruitSummary="I have  \(apple+oranges) pieces of fruit"//I have 8 pieces of fruit

5.数组和字典用[],感觉跟groovy一样啊

var array=["catfish","water","tulips","blue paint"]

array[1]

array[1]="bottle of water"

var occupations = [

    "malcolm":"Captain",

    "Kaylee":"Mechanic",

]

occupations["Jayne"]="Public Relations" //改了一个值,这语法貌似是跟groovy的map一样的

occupations  //这个直接起到了打印效果,至少在playground里是

6.空的数组和字典,指定类型的

let emptyArrary=String[]()

let emptyDictionary = Dictionary<String,Float>()

7.空的数组和字典,不指定类型的

let shoppinglist=[]

let dictionary=[:]  //如果类型能推断出来才用这里的两种写法

 

 

 

// Playground - noun: a place where people can play



import Cocoa



var myVariable=42

myVariable=50

let myConstant=42



let implicitInteger=70

let implicitDouble=70.0

let explicitDouble:Double=70



let explicitFloat:Float=4





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) piece of fruit"



let floatNumber:Float=4

let name="Ting"

let floatsummary="i am adding \(floatNumber+explicitFloat), haha \(name)"



var array=["catfish","water","tulips","blue paint"]

array[1]

array[1]="bottle of water"

var occupations = [

    "malcolm":"Captain",

    "Kaylee":"Mechanic",

]



occupations["Jayne"]="Public Relations"

occupations



let emptyArrary=String[]()

let emptyDictionary = Dictionary<String,Float>()



let shoppinglist=[]





let individualScores=[75,43,103,87,12]

var teamScore = 0

teamScore

for score in individualScores{

   "aaa"

    println(score)

}



"aaa"





for score in individualScores{

    if score > 50 {

        teamScore+=3

    } else {

        teamScore+=1

    }

    

}

teamScore







var optionalString:String? = "Hello"

optionalString == nil



var optionalName:String? = "John Appleseed"



var greeting = "Hello!"

if let name = optionalName{

    greeting = "Hello, \(name)"

} else if optionalName == nil {



    greeting = "Hello, nil"

}







let vegetable = "red pepper"

switch vegetable{

case "celery":

    let vegetableComment="Add some raisins and make ants on a log"

case "cucumber","watercress":

    let vegetableComment="That would make a good tea sandwich"

case let x where x.hasSuffix("pepper"):

    let vegetableComment="Is it a spicy \(x)?"

default:

    let vegetableComment="Everything tastes good in soup."

}







let interenstingNumber=[

    "prime":[2,3,5,7,11,13],

    "Fibonacci":[1,1,2,3,5,8],

    "Square":[1,4,9,16,25],

]



var largest = 0

var largestKind=""

for ( kind,numbers ) in interenstingNumber{

    for number in numbers {

        if number > largest{

        largest=number

        largestKind=kind

        }

    }

}

largest

largestKind



var n=2

while n < 100 {

n=n*2

}

n



var m=2

do{

m=m*2

}while m < 100

m



var firstLoop = 0

for i in 0..3 {

    firstLoop += i

}

firstLoop  //noticed 0..3 is 0, 1, 2 but not include 3, like python



var secondLoop = 0

for var i=0; i<3; i++ {

    secondLoop += i

}

secondLoop



var thirdLoop = 0

for i in 0...3 {

    thirdLoop += i

}

thirdLoop  //noticed 0..3 is 0, 1, 2 but not include 3, like python



func greet(name:String,lunch:String) ->String{

return "Hello \(name). Today's lunch is special \(lunch)!!!"

}



greet("Bob","Beef")







func getGasPrices()->(Double,Double,Double){

    return (3.49,3.59,3.69)

}



getGasPrices()







func sumOf(numbers: Int...) -> Int{

    var sum = 0

    for number in numbers {

        sum += number

    }

    return sum

}



sumOf()

sumOf(42,597,12)



5/2.0







func averageOf(numbers: Double...) ->Double{

    var average:Double = 0

    var sum:Double = 0

    numbers

    for number in numbers {

        sum += number

    }

    sum

    //var count:Double=numbers.count

    numbers.count == 3

    average = sum / 3

    var x:Double = Double(numbers.count)

    x

    sum

    651.0/3

    sum / x

    return average

    

}





averageOf(42,597,11)

651.0/3





func returnFifteen() -> Int{

    var y=10

    func add(){

        y += 5

        

    }

    y

    add()

    return y

}



returnFifteen()









func makeIncrementer() -> (Int -> Int){

    func addOne(number:Int)->Int{

    return 1 + number

    }

    return addOne

}

var increment=makeIncrementer()

increment(7)





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(numbers,lessThanTen)



numbers.map({

    (number:Int)-> Int in

    let result = 3 * number

    return result

    

    }

)







numbers.map({

    (number: Int)->Int in

    var result = 0

    if number % 2 == 1

    {

        result = 0

    }else {

     result = 3 * number

    }

    return result

    

    })







let x = numbers.map({number in 3 * number})

x









let bb=sort([1,5,3,12,2]){$0 > $1}

bb

let a = "hello"




"hello"

 
   

"aaa"

 
   

class Shape{

 
   

    let num=0

 
   

    var numberOfSides = 0

 
   

    func simpleDescription() -> String{

 
   

        return "A shape with \(numberOfSides) sides."

 
   

    }

 
   

    func simpleDescription2() -> String{

 
   

        return "A shape with \(num) sides."

 
   

    }

 
   

    

 
   

    

 
   

}

 
   

 

 
   

Shape().num

 
   

Shape().numberOfSides

 
   

 

 
   

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

 
   

    }

 
   

}

 
   

 

 
   

 

 
   

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

 
   

 

 
   

 

 
   

 

 
   

 

 
   

class Circle:NamedShape{

 
   

    

 
   

    var radius:Double

 
   

    

 
   

    init(radius:Double,name:String){

 
   

        self.radius = radius

 
   

        super.init(name: name)

 
   

    }

 
   

    func area()->Double

 
   

    {

 
   

        return 3.14 * radius * radius

 
   

    }

 
   

    

 
   

    override func simpleDescription() -> String {

 
   

        

 
   

        return "A Circle with radius=\(radius)."

 
   

    }

 
   

    

 
   

    

 
   

}

 
   

var circle = Circle(radius: 3, name: "smallCircle")

 
   

circle.area()

 
   

circle.simpleDescription()

 
   

 

 
   

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

 
   

    }

 
   

    }

 
   

    

 
   

    override func simpleDescription() -> String {

 
   

        return "An equilateral triagle with sides of length \(sideLength)."

 
   

    }

 
   

}

 
   

 

 
   

var triangle = EquilateralTriangle(sideLength:3.1,name:"a triangle")

 
   

triangle.perimeter

 
   

triangle.perimeter = 9.9

 
   

triangle.sideLength

 
   

 

 
   

class TriangleAndSquare{

 
   

    var triangle:EquilateralTriangle{

 
   

    willSet{

 
   

        square.sideLength = newValue.sideLength

 
   

    }

 
   

    }

 
   

    

 
   

    var square:Square{

 
   

    willSet{

 
   

        triangle.sideLength = newValue.sideLength

 
   

    }

 
   

    }

 
   

    

 
   

    init(size:Double, name:String){

 
   

        square = Square(sideLength:size, name:name)

 
   

        triangle = EquilateralTriangle(sideLength:size, name:name)

 
   

    }

 
   

    

 
   

}

 
   

var triangleAndSquare = TriangleAndSquare(size:10,name:"another test shape")

 
   

triangleAndSquare.square.sideLength

 
   

triangleAndSquare.triangle.sideLength

 
   

triangleAndSquare.triangle.perimeter = 90

 
   

triangleAndSquare.square.sideLength

 
   

triangleAndSquare.triangle.sideLength

 
   

 

 
   

triangleAndSquare.square = Square(sideLength:50, name:"larger square")

 
   

triangleAndSquare.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)

 
   

 

 
   

let optionalSquare: Square? = Square(sideLength:2.5, name:"optional square")

 
   

 

 
   

let sideLength = optionalSquare?.sideLength

 
   

 

 
   

 

 
   

 

 
   

 

 
   

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

 
   

        }

 
   

        

 
   

    }

 
   

}

 
   

let ace = Rank.Ace

 
   

let aceRawValue = ace.toRaw()

 
   

Rank.Ace.toRaw()

 
   

Rank.Ace.simpleDescription()

 
   

 

 
   

func compareRank(firstRank:Rank,secondRank:Rank) ->Int{

 
   

    

 
   

    var result:Int = firstRank.toRaw() - secondRank.toRaw()

 
   

    

 
   

    

 
   

    return result

 
   

}

 
   

 

 
   

 

 
   

let r = compareRank(Rank.Ace, Rank.Jack)

 
   

let x = r-1

 
   

let a = "hello"

 
   

let r2 = compareRank(Rank.Jack, Rank.Jack)

 
   

let r3 = compareRank(Rank.Jack, Rank.Six)

 
   

 

 
   

 

 
   

let a2 = "hello"

 
   

 

 
   

 

 
   

if let convertedRank = Rank.fromRaw(3){

 
   

    

 
   

    let threeDescription = convertedRank.simpleDescription()

 
   

}

 
   

 

 
   

 

 
   

 

 
   

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"

 
   

        }

 
   

    }

 
   

    func color() -> String{

 
   

        switch  self{

 
   

        case .Spades:

 
   

            return "black"

 
   

        case .Hearts:

 
   

            return "red"

 
   

        case .Diamonds:

 
   

            return "red"

 
   

        case .Clubs:

 
   

            return "black"

 
   

        }

 
   

        

 
   

    }

 
   

    

 
   

}

 
   

 

 
   

let hearts = Suit.Hearts

 
   

let heartsDescription  = hearts.simpleDescription()

 
   

 

 
   

Suit.Hearts.color()

 
   

Suit.Hearts.simpleDescription()

 
   

Suit.Clubs.color()

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

struct Card{

 
   

    var rank:Rank

 
   

    var suit:Suit

 
   

    func simpleDescription()->String{

 
   

        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"

 
   

    }

 
   

    

 
   

    func getDeck(){    // how ???

 
   

        

 
   

    }

 
   

    

 
   

}

 
   

 

 
   

let threeOfSpades = Card(rank: .Three, suit:.Spades)

 
   

threeOfSpades.simpleDescription()

 
   

 

 
   

threeOfSpades.getDeck()

 
   

 

 
   

 

 
   

 

 
   

enum ServerResponse {

 
   

    case Result(String,String)

 
   

    case Error(String)

 
   

    case myThree(String)

 
   

}

 
   

 

 
   

var success = ServerResponse.Result("6:00 am", "8:09 pm")

 
   

let failure = ServerResponse.Error("Out of cheese.")

 
   

success = ServerResponse.myThree("hahaha")

 
   

 

 
   

switch success{

 
   

case let .Result(sunrise, sunset):

 
   

    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."

 
   

case let .Error(error):

 
   

    let serverResponse = "Failure... \(error)"

 
   

case let .myThree(message):

 
   

    let serverResponse = "Welcome \(message)"

 
   

    

 
   

}

 
   

 

 
   

protocol ExampleProtocol{

 
   

    var simpleDescription: String {get}

 
   

    mutating func adjust()

 
   

}

 
   

 

 
   

 

 
   

class SimpleClass:ExampleProtocol{

 
   

    var simpleDescription: String  = "A very simple class."

 
   

    var anotherProperty: Int = 69105

 
   

    func adjust() {

 
   

        simpleDescription += "Now 100% adjusted."

 
   

    }

 
   

}

 
   

var ax = SimpleClass()

 
   

ax.adjust()

 
   

let aDescription =  ax.simpleDescription

 
   

 

 
   

struct SimpleStructure: ExampleProtocol{

 
   

    var simpleDescription:String="A simple structure"

 
   

    mutating func adjust(){

 
   

        simpleDescription += " (adjusted)"

 
   

    }

 
   

 

 
   

}

 
   

 

 
   

 

 
   

var bx = SimpleStructure()

 
   

bx.adjust()

 
   

let bDescription = bx.simpleDescription

 
   

"hello"

 
   

"aaa"

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

extension Int: ExampleProtocol{

 
   

    var simpleDescription:String{

 
   

    return "The number \(self)"

 
   

    }

 
   

    mutating func adjust(){

 
   

        self += 42

 
   

    }

 
   

 

 
   

}

 
   

 

 
   

7.simpleDescription

 
   

 

 
   

7.simpleDescription

 
   

 

 
   

 

 
   

let protocolValue:ExampleProtocol = ax

 
   

protocolValue.simpleDescription

 
   

//protocolValue.anotherProperty

 
   

 

 
   

func repeat<ItemType>(item:ItemType,times:Int)->ItemType[]{

 
   

    var result = ItemType[]()

 
   

    for i in 0..times{

 
   

        result += item

 
   

    }

 
   

    return result

 
   

}

 
   

 

 
   

repeat("knock", 4)

 
   

 

 
   

enum OptionalValue<T>{

 
   

    case None

 
   

    case Some(T)

 
   

}

 
   

var possibleInteger: OptionalValue<Int> = .None

 
   

possibleInteger = .Some(100)

 
   

 

 
   

 

 
   

 

 
   

func anyCommonElements < T,U where T:Sequence, U:Sequence, T.GeneratorType.Element:Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs:T,rhs:U) ->1[]{

 
   

    for lhsItem in lhs

 
   

    {

 
   

        for rhsItem in rhs{

 
   

            if lhsItem == rhsItem{

 
   

            

 
   

            }

 
   

        

 
   

        }

 
   

    

 
   

    }

 
   

    return false

 
   

}

 
   

"hello"

 
   

anyCommonElements([1,2,3], [3])

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 
   

 

 

 

你可能感兴趣的:(swift)