IOS移动开发从入门到精通 swift进阶

函数

func
1 func sayHelloSwift()
2 {
3 print(“Hello, Swift!”)
4 }

1 func sum(number1:Int, number2:Int)->Int
2 {
3 return number1 + number2
4 }

num1:Int,String ->Int

return ((number1 < number2)?number1:number2)


Bool
Int
String

返回元组

1 func getUserInfo(userId:String) -> (userName:String,
userLevel:Int, photoPath:String)
2 {
3 let userName = “John”
4 let userLevel = 3
5 let photoPath =
“http://www.coolketang.com/userPhoto/323sfa4.png”
6
7 return (userName, userLevel, photoPath)
8 }


内置函数

abs
min
max
filter
1 for i in (1……10).filter({0 * 3})
2 {
3 print(i)
4 }
reduce
1 let result = (1……4).reduce(0, combine:{1})
2 print(result) //输出结果:10

1 let result = (1……4).reduce(0, combine:*)
2 print(result) //输出结果:24

枚举 enum

1 enum UserLevel
2 {
3 case 总经理
4 case 区域经理
5 case 主管
6 case 业务员
7 }

enum

1 let userLevel = UserLevel.业务员
2 switch userLevel
3 {
4 case UserLevel.总经理:
5 print(“总经理登录系统后,进入系统配置页面。”)
6 case UserLevel.区域经理:
7 print(“区域经理登录系统后,进入区域报表页面。”)
8 case UserLevel.主管:
9 print(“主管登录系统后,进入业务员任务签发页面。”)
10 case UserLevel.业务员:
11 print(“业务员登录系统后,进入报备客户页面。”)
12 default:
13 print(“无法进入客户报备页面,请重新登录!”)
14 }

enum

1 enum Gender:UInt8
2 {
3 case Male = 1
4 case Female = 2
5 case Unknow = 3
6 }

结构 struct

1 struct Animal {
2 let zooName:String = “Beijing Zoo”
3 var name:String
5 func say()
6 {
7 print(“Hi, I’m (name).”)
8 }
9 }

类 class

1 class Car
2 {
3 var brand:String
4 var speed:Int
5 init()
6 {
7 self.brand = ””
8 self.speed = 0
9 }
10 init(brand:String, speed:Int)
11 {
12 self.brand = brand
13 self.speed = speed
14 }
}

初始化

1 let car = Car()
2 car.brand = “Audi”
3 car.speed = 80

属性同时设置:

class A{
4 var level:Int
5 {
6 get
7 {
8 return self.damage / 10
9 }
10 set(newLevel)
11 {
12 self.damage = newLevel * 10
13 }
14 }
}

类方法:class func xx(n1:Int,n2:Int)->Int

1 class MathTool
2 {
3 class func sum(number1:Int, number2:Int) -> Int
4 {
5 return number1 + number2
6 }
7 class func multiply(number1:Int, number2:Int) -> Int
8 {
9 return number1 * number2
10 }
11 }

析构函数

deinit
{
print(“Delete the fileManager.”)
}

继承:class Dog:Animal

重载:override func say()

父类初始化;super.init(name:name)

延迟加载:lazy

5 class User
6 {
7 var name:String = “John”
8 lazy var avarta:Avarta = Avarta()
9 }

类型判断:if ix is Int

类型转换:xx as Int

任何类型数组:var sa=Any

1 var anythings = Any
2 anythings.append(8)
3 anythings.append(3.1415)
4 anythings.append(“hello”)
5 anythings.append((3.0, 5.0))

结构扩展: extends Cat

接口类:protocol

protocol Walking
{
var damage:Int{get set}
func walk()
}

空值:nil

var password:String?
print(password?.characters.count)

属性的willSet didSet

1 class Hero
2 {
3 var damage:Int = 10
4 var level:Int = 1
5 {
6 willSet
7 {
8 print(“即将为level设置新值:(newValue)。”)
9 }
10 didSet
11 {
12 if level>oldValue
13 {
14 print(“你的英雄升级了!”)
15 }
16 else
17 {
18 print(“挑战失败,英雄未能升级。”)
19 }
20 }
21 }
22 }

你可能感兴趣的:(IOS移动开发从入门到精通 swift进阶)