Swift Tips

前端之家收集整理的这篇文章主要介绍了Swift Tips前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Int和cpu架构有关

在32位cpu上(iphone5及以前)是Int32,64位上(5s及以后)为Int64。UInt同理。

可选链式调用

可选链式调用失败时,等号右侧的代码不会被执行

  1. func createAddress() -> Address {
  2. print("Function was called.")
  3. return Address()
  4. }
  5. john.residence?.address = createAddress() // 不会输出打印

@autoclosure

autoclosure可以把表达式转化为闭包。

  1. func judgeLog(@autoclosure predicate: () -> Bool,msg: String) {
  2. if predicate() {
  3. print(msg)
  4. }
  5. }
  6. judgeLog(2>1,msg: "2 > 1 is right")

assert & fatalError

assert是Debug时才起效,Release下不起效。而fatalError无论哪种情况都起效。可以按照需求来选择错误奔溃处理。

mutating

mutating修饰方法,用在struct,enum这些值类型中,他们的方法修改属性必须使用mutating。

infix,prefix,postfix

添加自定义操作符时,分别加上infix表示中位符 prefix前位符 postfix后位符。

  1. infix operator +* {
  2. associativity none //结合律,
  3. precedence 160 //优先级,乘除为150,加减为140
  4. }
  5. // 重载+*
  6. func +* (left: Int,right: Int) -> Int {
  7. return (left * right + left + right)
  8. }

inout

函数的参数默认是let,如果有时候需要修改传入的变量的值,需要添加inout关键字。

Designated & Convenientce & required

designated初始化方法就是最普通的init方法。designated方法必须确保所有成员对象被初始化了。
初始化方法中依赖其他初始化方法,必须使用convenience。若父类实现了convenicence init那么子类可以直接使用父类这个方法来初始化。
required是强制子类必须重写的关键字。

初始化方法返回nil

init后加"?"或"!"允许在初始化中返回nil来实例化optional对象。

类型混合

  1. let mixed1: [Any] = [1,"two",3.0]
  2. let mixed2 = [1,3.0] // [NSObject]
  3. enum IntOrString {
  4. case IntValue(Int)
  5. case StringValue(String)
  6. }
  7. let mixed3 = [IntOrString.IntValue(1),IntOrString.StringValue("haha")]

dynamicType获取动态类型

  1. protocol Copyable {
  2. func copy() -> Self
  3. }
  4. class MyClass: Copyable {
  5. var num: Int
  6. required init(num: Int) {
  7. self.num = num
  8. }
  9. func copy() -> Self {
  10. let result = self.dynamicType.init(num: self.num)
  11. return result
  12. }
  13. }

多重optional

  1. let aNil: String? = nil
  2. let bNil: String?? = aNil
  3. let cNil: String?? = nil // bNil不等于cNil

lldb调试命令

运行时,lldb调试直接使用po指令可以打印对象的值 (po = print object)
使用bt可以打印出现场堆栈信息
使用fr v xxx打印桢信息,"fr v -R xxx"来打印多重变量信息

map方法

  1. let arr = [1,2,3]
  2. let doubled = arr.map({
  3. $0 * 2
  4. })
  5. print(doubled) // [2,4,6]
  6.  
  7. let num: Int? = 6
  8. let result1 = num.map {
  9. $0 * 2
  10. }
  11. print(result1) // Optional(12)

where用法

  1. let name = ["li ming","wang hao","xiao bai"]
  2. name.forEach { (_name) in
  3. switch _name {
  4. case let x where x.hasPrefix("xiao"):
  5. print("[\(x)] is my family")
  6. default:
  7. print("[\(_name)] is not my family")
  8. }
  9. }
  10.  
  11. let score: [Int?] = [99,100,nil,60]
  12. score.forEach {
  13. if let s = $0 where s == 100 {
  14. print("you are so smart!")
  15. }
  16. }

在拓展中也可以这么使用

  1. extension Array where Element: Integer {
  2. // ...
  3. }

类型方法

实例方法是被类型的某个实例调用方法。你也可以定义类型本身调用方法,这种方法就叫做类型方法。只需要在func前添加class。类型方法内部self指向这个类型本身,而不是类型的某个实例。

  1. class MyClass {
  2. class func method() {}
  3. }
  4. MyClass.method()

实例方法的动态调用

  1. class MyClass {
  2. func method(number: Int) -> Int {
  3. return number + 1
  4. }
  5. }
  6. let f = MyClass.method // 等价于let f = { (obj: MyClass) in obj.method }
  7. let object = MyClass()
  8. let result = f(object)(1) // 2

如果加入重载和类方法

  1. class MyClass {
  2. class func method(number: Int) -> Int { // #1
  3. return number
  4. }
  5. func method(number: Int) -> Int { // #2
  6. return number + 1
  7. }
  8. func method(numberA: Int,numberB: Int) -> Int { // #3
  9. return numberA + numberB
  10. }
  11. }
  12. let f0 = MyClass.method // 等价于类型方法 #1
  13. let f1: Int -> Int = MyClass.method // 等价于f0
  14. let f2: MyClass -> Int -> Int = MyClass.method // #2
  15. let f3: MyClass -> (Int,Int) -> Int = MyClass.method // #3
  16.  
  17. let object = MyClass()
  18. let result0 = f0(1) // 1
  19. let result1 = f1(1) // 1
  20. let result2 = f2(object)(1) // 2
  21. let result3 = f3(object)(2,2) // 4

条件编译

  1. #if <condition>
  2. // ...
  3. #elseif <condition>
  4. // ...
  5. #else
  6. // ...
  7. #endif

条件可以是os(OSX)/os(iOS),arch(x86_64)/arch(arm)/arch(arm64)/arch(i386)
也可以是自定义的一个条件变量:Build Settings->Swift Compiler->Custom Flags添加-D CONDITION_NAME

可选接口

  1. // # 1 使用objective-c方式
  2. @objc protocol OptionalProtocol {
  3. optional func optionalMethod()
  4. func necessaryMethod()
  5. }
  6. // # 2 使用接口拓展
  7. protocol OptionalProtocol {
  8. func optionalMethod()
  9. func necessaryMethod()
  10. }
  11. extension OptionalProtocol {
  12. func optionalMethod() {}
  13. }

随机

使用arc4random_uniform(arc4random在32位iPhone上有时程序奔溃)

  1. // # 1
  2. let maxValue: UInt32 = 10
  3. print(Int(arc4random_uniform(maxValue)) + 1)
  4.  
  5. // # 2
  6. func randomInRange(range: Range<Int>) -> Int {
  7. let count = UInt32(range.endIndex - range.startIndex)
  8. return Int(arc4random_uniform(count)) + range.startIndex
  9. }
  10. for _ in 1...10 {
  11. print(randomInRange(1...10))
  12. }

引用

100个Swift必备Tips
Swift教程

猜你在找的Swift相关文章