首页 > 代码库 > swift语言初见

swift语言初见

以下是swift得基础语法部分内容

//  main.swift

//  helloSwift

//

//  Created by cyteven on 14-7-23.

//  Copyright (c) 2014 cyteven. All rights reserved.

//


import Foundation

//打印字符串

println("Hello, World!")

//变量定义

var  a = 10

var  b = 20

//常量定义

let c = a + b

println(c)

//变量类型定义

var i:Int = 4

var s:String ="i was string"

print(i)

println(s)

//字符串链接1

var helstr = "hello"

var tak = helstr + "hi"

println(tak)

//字符串链接2

var nNum = 1000

var sGood = "good"

var sResStr = "\(sGood)afasdfasfd\(nNum)"

println(sResStr)

//数组的使用

var attr = ["wocao","zahuishi",2000,12.4]

println(attr)

println(attr[0])

println(attr[1])

println(attr[2])

println(attr[3])

var attrStr = [String]()

//字典

var dict:Dictionary = ["name":"cyteven","age":26]

dict["class"] ="good"

dict["score"] =100

println(dict)

//if for

var start = 0

for start in 0...100 {

    if start%2 == 0 {

        println(start)

    }

}


var myName:String? ="cyteven"


if let name = myName {

    println("kaixin\(myName)")

}


//函数

func sayToYou(name:String){

    println("i want to say you\(name)")

}

sayToYou(" cyteven")

//有返回值得函数

func getTwoNum(index:Int)->(Int,Int){

    var numArray1 = [0,1,2,3,4,5,6];

    var numArray2 = [0,1,2,3,4,5,6];

    return (numArray1[index],numArray2[index+1])

}

let (num1:Int,num2:Int) =getTwoNum(3)

println(num1+num2)

//函数定义为变量

var sayHello = sayToYou

sayHello("myname")


//swift面向对象


class myPet{

    var _name:String

    var _age:Int

    

    init(name:String,age:Int){

        self._name = name

        self._age = age

    }

    

    func getPetAge()->(Int){

        return self._age

    }

    

    func getPetName()->(String){

        return self._name

    }

}


var pet = myPet(name:"mengmengda",age:2)

var petName:String =pet.getPetName()

var petAge:Int = pet.getPetAge()

println("my pet name is\(petName),it is\(petAge) years old")


//继承

class myDog:myPet{

    var _color:String

    

    init(name: String, age:Int,color:String){

        self._color = color

        super.init(name: name, age: age)

    }

    

    func getDogColor()->(String){

        return self._color

    }

    

    override func getPetName() -> (String){

        return ("wangwang \(self._name)")

    }

}


var dog = myDog(name:"xiaoQ", age:3, color: "black")

var dogName = dog.getPetName()

var dogAge = dog.getPetAge()

var dogColor = dog.getDogColor()

println("I have a \(dogColor)  dog named \(dogName),its \(dogAge) years old.")