变量声明
//变量声明
var num = 22;
var m:Int = 10;
num = 15;
常量的声明
let count = 50;
let width:Double = 12.0;
//count = 13;//count为常量 不能被改变
字符串声明
let label = "The width is";
var label1:String = "你好";
变量类型转换
swift语言中类型没有隐式转换,所有类型只能强制转换
let widthLabel = label + String(count);
var d:Double = width + Double(count);
在字符串中打印值
println(label + "\(count)");
println("this is \(count)");
println("this is \(m)");//m为Double类型
println("this is \(m + n)");//m和n都为Double类型
数组声明与使用
var shopping = ["water","paper","tulips"];//定义一个数组
println(shopping[0]);
var emptyArry = [String]();//声明一个空的String数组
shopping = [];//如果类型可以被推断的话可以这样声明一个空数组
字典的声明是使用
var occupation = [
"hello" : "world","good" : "morning"
]
var str = occupation["good"];
var emptyDic = [String:Float]();//声明一个空的字典
var dic = [:];//类型知道的话可以这样声明一个空字典
控制语句
for语句
//for控制语句
for(var i = 0; i < shopping.count; i++) {
println(shopping.count);
println(shopping[i]);
}
//新型for循环
for i in 0..<3 {
forstLoop += i;
}
相等于
for var i=0; i<3; i++ {
forstLoop += i;
}
switch语句
switch语句不需要加break语句,语句执行以后会自动跳出。
//switch
let str1 = "hello";
switch str1 {
case "hello":
println("hello world");
case "good":
println("good morning");
default://default语句必须有,不然会报错
println("error");
}
使用for in便利字典和数组
let intNumbers = [
"one" : [2,3,4,5,5],"two" : [1,6,8],"three" : [6,89,3]
]
var largest = 0;
for(kind,numbers) in intNumbers {
//number前不用加var
for number in numbers {
if(number > largest) {
largest = number;
}
}
}
println("the largerst number is \(largest)");
带有?号的变量声明
var optionString:String? = "hello";//表示optionString可以为nil,可以是确定值
println(optionString == nil);
var optionName:String? = "John Appleseed";
var greeting = "Hello";
if let name = optionName {//使用if let处理值缺失的情况
greeting = "Hello,\(name)";//"Hello,John Appleseed"
}
函数
返回一个参数
//后面的String是返回值类型
func greet(name:String,day:String) -> String {
return "Hello \(name),Today is \(day)";
}
println(greet("ttf","friday"));
返回多个参数(返回元组)
//参数是一个数组,返回值为最小值,最大值,总和
func calculte(scores:[Int]) ->(min: Int,max: Int,sum: Int) {
var min = scores[0];
var max = scores[0];
var sum = scores[0];
for score in scores {
if score < min {
min = score;
}else if score > max {
max = score;
}
sum += score;
}
return (min,max,sum);
}
let scores = [1,2,7];
calculte(scores);
可变参数的函数
//有不确定个参数
func sumOf(numbers: Int...) -> Int {
var sum = 0;
for number in numbers {
sum += number;
}
return sum;
}
sumOf(1,3);
函数里面可以嵌套函数
//函数里面嵌套一个函数
func returnFifteen() -> Int {
var y = 10;
func add() {
y += 5;
}
add();
return y;
}
returnFifteen();
函数返回一个函数
函数是swift里面的一级成员,最大,所以他也可以返回一个函数
//返回值是一个函数
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number;
}
return addOne;
}
var increment = makeIncrementer();
increment(2);//给这个函数传递参数
函数作为参数传递
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,10,56];
hasAnyMatches(numbers,lessThanTen);
函数是特殊的闭包?
//让每一个元素都乘以3
numbers.map({
(number: Int) -> Int in let result = 3 * number;
return result;
})
如果参数类型都已经知道,下面这种方法等价
//让每一个元素都乘以3,并打印
let mappedNumber = numbers.map({number in 3 * number});
println(mappedNumber);
//从大到小排列数组
let sortedNumbers = sorted(numbers) { $0 > $1 };
println(sortedNumbers);
类的声明与使用
声明一个类
class Shape {
var numberOfSide = 0;
func simpleDescription() -> String {
return "this is \(numberOfSide)";
}
}
类对象创建与使用
var shape = Shape();//创建类对象
shape.numberOfSide = 2;//给类的成员变量赋值
var shapeDes = shape.simpleDescription();//调用类的成员函数
类的构造方法
var shape = Shape();
shape.numberOfSide = 2;
var shapeDes = shape.simpleDescription();
class NameShape {
var numberOfSides: Int = 0;
var name: String;
init(name: String) {//构造方法
self.name = name;
}
func simpleDescription() -> String {
return "this is \(numberOfSides)";
}
}
var nameShape = NameShape(name:"ttf");//方法传递参数时,前面要加标记
nameShape.simpleDescription();
类的继承
class Square: NameShape {
var sideLength: Double;
init(sideLength: Double,name: String) {
self.sideLength = sideLength;
super.init(name: name);//不能写在前面,要保证本类中先定义的先初始化
self.numberOfSides = 4;
}
func area() -> Double {
return self.sideLength * self.sideLength;
}
override func simpleDescription() -> String {
return "square sides of length is \(self.sideLength)";
}
}
var square = Square(sideLength: 10.0,name: "ttf");
square.area();
square.simpleDescription();
类方法传参的时候需要显示说明
类中的方法和一般的函数不同,类中的方法传递参数的时候需要有标记,显示说明(第一个可以省略)
class Counter { var count: Int = 0; func increment(amout: Int,times: Int) { count += amout * times; } } var counter = Counter(); counter.increment(2,times: 4);//必须要带标记,显示声明
枚举和结构体
枚举的声明,里面也可以有方法
enum Suit {
case one,two,tree
}
let number = Suit.one;
结构体创建
结构体和类很想同,结构体是传值,类是传引用
协议和扩展
协议声明
protocol EcampleProtocol {
var simpleDescri: String{get};
mutating func adjust();
}
类只要继承协议就可以实现里面的方法了
扩展
extension Int: ExampleProtocol { mutating func adjust() { self += 42; } }