Swift入门第二天
最近的天气真的很奇怪,但是还是需要继续在Swift上下功夫,接下来我来介绍下swift中相关知识点,如:元组,数组,字典,结构,枚举类型,函数定义,逻辑判断,for循环。这些语法在其他热门语言中也是必备的知识点,接下来给一段代码,相信大家运行后一定会有所掌握。
上次忘了告诉大家如何创建可运行的Swift程序,接下来我用图示的方式说明下:
第一步:打开Xcode,选择Project,进入如下界面:
点击Next,选择Swift语言,并填写完整项目名。next后,选择程序存放位置就搞定了.基本语法学习通过创建这个工程就可以了
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //1.元组 var 元组 = (120,"test"); //可以关联不同的类型 元组.0 元组.1 //tuple let httpStatus = (statusCode:404,statusDesc:"Not Found"); httpStatus.statusCode; httpStatus.statusDesc; httpStatus.0 httpStatus.1 //2.数组 var shoppingList = ["string",120,35.5,true]; shoppingList[0]; shoppingList[1]; shoppingList[2]; if (shoppingList.isEmpty) { print("数组为空"); } else { print("数组非空"); } shoppingList.count shoppingList.append("水费"); shoppingList.append("电费"); shoppingList.append("网费"); shoppingList += ["hello","world","tom"]; shoppingList var firstItem = shoppingList[1]; shoppingList[1...5] = ["西瓜","南瓜","冬瓜"]; shoppingList var someInts = [Int32](); //数组的初始化 someInts.append(1); someInts //someInts.append("test"); //类型不一致 someInts //3.字典 var games:[String:String] = ["暗黑":"1级","仙剑":"2级","CS":"3级"]; games games["CS"] let keyValue = ["k1":"v1","k2":"v2","k3":"v3"]; keyValue["k2"]; //字典的遍历 for item in keyValue.values { print("项次依次是:\(item)"); } //初始化一个字典 var numberValue = [Int32:String](); numberValue[16] = "sixteen"; numberValue //结构,swift的区别:结构体里面可以定义方法 struct Sword { var length : Float; let name:String; func description() { print("这是一个名字为\(name)的武器,长度\(length)"); } } var sword:Sword = Sword(length: 1.2, name: "巨阙"); //枚举类型 enum FlatForm { case Windows case Mac case Linux } var OS:FlatForm = FlatForm.Windows; //函数定义 func sayHello(personName:String)->String { return "hello welcome"; } func say()->Int32 { return 0; } sayHello("kitty"); say(); func sayHelloLabel(personNameLabel personName:String)->String { return "hello world"; } sayHelloLabel(personNameLabel: "tom"); var a = 10; var b = 20; var addResult = a + b; var subResult = a - b; var mutResult = a * b; var divResult = a / b; var remainResult = a % b; var sum = 0; sum += a; //逻辑判断 1==1 1>2 //三目运算符 ?: var flag = true; var viewHeight = 480 + (flag ?88:0); //for 循环 var sum2 = 0; for i in 1...10 { //i++; sum += i; }