LaneBlog

蝼蚁虽小,也有梦想

PHP Socket服务 | PHP微信开发框架 | 开源博客

初探Swift一 - 变量与数据类型

Clicks: 2095 Date: 2015-01-06 10:36:59 Power By 李轩Lane

swift ios

    

    初探Swift,Swift变量声明,let和var分别声明常量和变量。Swift数据类型,包括整型,浮点型,字符型,布尔型,可选型等,已经强制类型转换和if选择。

//-----------变量相关----------

//常量

let maxNum = 1000

//变量

var index = 0


var a=0.0, y=0, z=0

a = 1;

a = 1.1;

//报错

//a = "a";


//显示申明类型

var test : Int

test = 10


var red, green, blue : Int

//十进制

red = 17;

//二进制,以0b开头

red = 0b10001

//八进制,以0o开头

red = 0o21

//十六进制,以0x开头

red = 0x11


//科学计数法

let b = 0.012

let c = 1.2e-2


//多位整数的表示法

let e = 1000000

let f = 1_000_000

let g = 1_000_000


//自动类型转换

let h:Float = 1

//Xcode beta2会将1.2转为1,而Xcode beta3直接报错。

//let i:Int = 1.2


//强制类型转换

let j:Double = Double(h) + b


//变量名,任何unicode都可以

let 姓名 = "小明"

println(姓名 + " 你好")




//----------选择-----------

let bool1 = true

let bool2:Bool = false


//即使语句块只有一行,花括号{}也不能省略,在选择里,只有truefalse10都是不可以的。

if bool1{

    println("hello");

}else if bool2{

    println("world");

}else{

    println("swift");

}




//---------元组-----------

let tuples_1 = ("小明", "", 21, true)

//元组可以赋值给变量

let (name, sex, age, status) = tuples_1

println("姓名:"+name+",性别:"+sex);

//元祖可以用.0.1.2来访问

println("姓名:"+tuples_1.0+",性别:"+tuples_1.1);


//每个元祖都赋一个key

let tuples_2 = (date:"2015-01-05", time:"16:06", author:"lane")

println("日期:"+tuples_2.date+" "+tuples_2.time+",作者:"+tuples_2.author);

println("日期:"+tuples_2.0+" "+tuples_2.1+",作者:"+tuples_2.2);


//至提取元组的第一个值,不关心后面的值

let login = (true, "小明")

let (staic, _) = login

if staic{

    println("hi");

}else{

    println("hi hi");

}

//元组的类型显示声明

let login2:(Bool, String) = (true, "小明")



//可选型optional

var optionalVar1:Int?

optionalVar1 = 1


let userAge = "18"

var age = userAge.toInt()


if(age != nil){

    println("You age is " + String(age!) )

}else{

    println("Invalidate userInput")

}


//解包

if let userInput = userAge.toInt(){

    println("you age is \(userInput)");

}

let m:String? = "hello";

let n:String! = "hi";

©2014 www.lanecn.com , All rights reserved. Power By Li Xuan.  京ICP备14005030号