IOS Swift 訓練

jackchain發表於2014-06-07
// Playground - noun: a place where people can play

import Cocoa

var str = "Hello, playground"

str+=",Yes I'm Good";

println("hello swift")

var myvar=23

myvar=18
let myConstant=42
var a:Double=10

let label="this width is"
let width=94
let widthlabel=label+String(width)


"I have \(width) apples."
"I have \(String(width)+String(width)) apples"
var shoppingList=["C","B","D","E"]
shoppingList[0]="A"
shoppingList
var dict=["A":"yes","B":"no"]
dict["A"]
dict["C"]="Cancel"
dict
var emptyArray=String[]()
emptyArray.append("A")
emptyArray.append("C")
emptyArray

var emptyDict=Dictionary<String,Float>()
emptyDict.values
emptyDict=["A":1,"B":2,"C":4]

let individualSocres=[1,2,45,6,2,0]
var teamScore=0
for score in individualSocres{
    if(score>8){
        teamScore+=3
    }
    else{
        teamScore+=1
    }
}
teamScore
var optional:String?="Hello"
optional=nil
var t="H"
if optional==nil {
    t="hello \(optional)"
}else{
    t="XX"
}

let vegetable="1cecery"
switch vegetable{
    
//Case 用法
case let x where x.hasSuffix("cery"):
    let v="Is it a spicy \(x)"
    
    case "cecery":
        let v="add some";
    case "cecery","":
        let v="tttt"
    default:
        let v="tastes good"
}


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
        }
    }
}
largest

var n=2
while n<100{
    n=n*2
}

var firstForLoop=0
for i in 0..10{
    firstForLoop+=i
}

//多返回值引數
func greet(name:String,day:String)->(String,Double){
    return ("hello \(name),today is \(day)",99.0)
}

greet("jack","2014-06-09")

//陣列引數
func sumOf(numbers:Int...)->Int{
    var sum=0;
    for num in numbers{
        sum+=num
    }
    return sum
}

sumOf()
sumOf(19,0,3)

//巢狀函式
func returnFifteen()->Int{
    var y=10;
    func add(){
        y+=5;
    }
    //呼叫了才執行
    add()
    return y;
}

returnFifteen();

//函式可以作為另一個函式的返回值
func makIncrementer() -> (Int->Int){
    func addOne(number:Int)->Int{
        return 1+number;
    }
    return addOne;
}

var increment=makIncrementer();
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)

//類定義
class Animals{
    var name="";
    //建構函式
    init(name:String){
        self.name=name;
    }
    //方法
    func WhatsName()->String{
        return "my name is \(name)!";
    }
}
//注意建構函式的呼叫方式
var cat=Animals(name: "dog");
//cat.name="cat";
cat.WhatsName();

//類的繼承
class Pig:Animals{
    var age:Int{
        //在設定之前可以執行某段程式碼,之後執行用didSet
        willSet{
            println("aaaa");
        }
    };
    
    //Getter And Setter
    var Age:Int{
        get{
            return age;
        }
        set{
            age=newValue;
        }
    }
    
    init(age:Int){
        self.age=age;
        super.init(name:"Pig");
    }
    
    func HowOld()->String{
        return "pig is \(age) years old";
    }
    //重寫
    override func WhatsName()->String{
        return "pig is a clever animal!";
    }
    
}

let LittlePig=Pig(age:3);
LittlePig.HowOld();
LittlePig.WhatsName();
LittlePig.age;
LittlePig.age=4;
LittlePig.Age=8;



class Counter {
    var count: Int = 0
    //方法引數名,可以在為方法體內部使用單獨定義一個別名,例如times
    func incrementBy(amount a: Int, numberOfTimes times: Int) {
        count += a * times
    }
}
var counter = Counter()
counter.incrementBy(amount:2, numberOfTimes: 7)

//?之前如果為nil,則之後的會被忽略,否則執行
var os:String;//?="hello jack";
var ai:String?="BBBBB"

//列舉
enum Rank: Int {
    case Ace = 1,Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,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()
ace.simpleDescription();
//struct結構體,值型別,類為引用型別
enum ServerResponse {
    case Result(String, String)
    case Error(String)
}

let success = ServerResponse.Result("36:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")

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)"
}

//介面和擴充套件
protocol IUser{
    var simpleDesc:String{get}
    mutating func addJust()
}

class SimpleClass:IUser{
    var simpleDesc:String="Very well";
    func addJust(){
        simpleDesc+=" Now implement";
    }
}

var test=SimpleClass();
test.addJust()
test.simpleDesc;

//介面是可以用來擴充套件型別的功能的
extension String: IUser {
    var simpleDesc: String {
        return "The number \(self)";
    }
    mutating func addJust() {
        self += "S";
    }
}
"OK".simpleDesc
let tx:IUser = test;
tx.simpleDesc

//範型
func repeat<T>(item: T, times: Int) -> T[] {
    var result = T[]()
    for i in 0..times {
        result += item
    }
    return result
}
repeat("knock", 4)

func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

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

 

相關文章