swift学习

Swift 文档读后随写

2016-03-23  本文已影响86人  smile丽语

一. 常量&变量

简单体验

// 定义变量
var i = 10
print(i)
i = 15
print(i)

let j = 20
// 常量一经定义不能自改数值
//        j = 25
print(j)

定义 OC 对象

// 实例化视图
let v = UIView(frame: CGRectMake(0, 0, 100, 100))
// 设置背景颜色
v.backgroundColor = UIColor.redColor()

// 添加到根视图
view.addSubview(v)

常量&变量的使用原则:尽量先用 let,只有需要变的时候,再用 var,能够更加安全

变量类型

let x = 10
let y = 10.5
let z: Double = 20

print(Double(x) + y)
print(x + Int(y))
print(y + z)

二. 逻辑分支

简单体验

var i = 10

if i > 0 {
    print("OK")
}

三目

var a = 10
var b = 50

var result = a > b ? a : b
print(result)

可选项

演练 1

let url = NSURL(string: "http://www.520it.com/")

if url != nil {
    NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, _, _) -> Void in
        print(NSString(data: data!, encoding: NSUTF8StringEncoding))
    }).resume()
}

convenience init?(string URLString: String)


    * 如果有 `?` 表示改方法有可能无法实例化到正确的对象
    * 这种函数返回的对象,被称为 `可选项`,即有可能有值,也有可能没有值
    * 实际开发时,需要针对这种对象加以判断,并且在分支内部使用 `!`,指明改对象确实是存在的
    * 相比在 `OC` 的开发,尤其在日常练习时,会给定一个能够运行的值,而在实际运行时,一旦条件不满足,会直接闪退,这样用户体验会非常不好

> `Swift` 的设计者考虑到因为对类型的强制要求,会让代码很难看,因此提供了一个变通的解决方案

### 演练 2

```swift
if let url = NSURL(string: "http://520it.com") {
    NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, _, _) -> Void in
        print(NSString(data: data!, encoding: NSUTF8StringEncoding))
    }).resume()
}

演练3

var name: String?
print(name?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

name = "lnj"
print(name?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

let l = 10
print(l + (name?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) ?? 0))

三. 循环

OC风格的 for

// 传统写法
for var i = 0; i < 10; i++ {
    print(i)
}

Swift风格的 for

// 遍历 0 ~ <10
for i in 0..<10 {
    print(i)
}

print("---")

// 遍历 0 ~ 10
for i in 0...10 {
    print(i)
}

特殊写法

for _ in 0...10 {
    print("hello")
}

四. 字符串

在 Swift 中绝大多数的情况下,推荐使用 String 类型

使用 String 的原因

遍历字符串

let str = "我要飞的更High"

for s in str {
    print(s)
}

字符串拼接

let str1 = "zhangsan"
let str2 = "lisi"
let i = 10

print(str1 + str2)
print("\(str1) \(str2) \(i)")

格式化字符串

for _ in 0...10 {
    let str = String(format: "zhangsan - %04d", arguments: [arc4random_uniform(100)])
    print(str)
}

String & Range 的结合

以下是超级费劲的代码

let str: String = "我要飞的更High"

var subStr = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex))
print(subStr)

建议写法

let str1: NSString = "我要飞的更High"
print(str1.substringWithRange(NSMakeRange(0, 3)))

五. 数组

简单体验

let arr = ["zhangsan", "lisi"]
print(arr)

// 遍历每一个元素
for a in arr {
    print(a)
}

// 像 OC 一样打印
print(arr as NSArray)

数组中保存的对象类型

// 数组中保存的都是字符串
let arr = ["zhangsan", "lisi"]

// 数组中保存的是 NSObject
let arr1 = ["zhangsan", 1]

常见数组操作

// 定义只能保存字符串类型数组
var array: [String]

// 初始化数组
array = ["zhangsan"]

// 添加元素
array.append("lisi")

print(array)

// 删除元素
array.removeAtIndex(1)
print(array)

// 删除所有元素
array.removeAll(keepCapacity: true)
print(array.capacity)

// 注意数组容量的变化
for i in 0..<10 {
    array.append("\(i)")
    print("\(array) --- \(array.capacity)")
}

// 实例化新的数组
var array2 = [String]()
array2.append("1")
array2.append("2")

// 拼接数组
array += array2

print(array)

六.字典

/// 定义并实例化字典
var dict = [String: AnyObject]()

dict["name"] = "zhangsan"
dict["age"] = 18

print(dict)

// 设置相同 key,之前的数值会被覆盖
dict["name"] = "lisi"
print(dict)

// 删除某一个 key
dict.removeValueForKey("age")
print(dict)

dict["title"] = "manager"
print(dict)

// 遍历字典(k, v可以随便写)
for (k, v) in dict {
    print("\(k) -- \(v)")
}

// 合并字典
var dict2 = ["name": "wangwu", "age": 80, "title": "boss"]
for (k, v) in dict2 {
    dict.updateValue(v, forKey: k)
}
print(dict)

七. 函数

简单演练

func sum(a: Int, b: Int) -> Int {
    return a + b
}

参数名的特殊处理

强制要求参数名

func sum1(x a: Int, y b: Int) -> Int {
    return a + b
}

省略参数名

func sum2(a: Int, _ b: Int) -> Int {
    return a + b
}

八. 闭包

weak var weakSelf = self
demo("zhangsan") { (_) -> Int in
    print(weakSelf?.view.backgroundColor)

    return 20
}

九. 懒加载

lazy var demoView: UIView = {

    let v = UIView(frame: CGRectMake(10, 10, 100, 100))
    v.backgroundColor = UIColor.redColor()

    return v
}()
lazy var 变量: 类型 = { 创建变量代码 }()

十. getter & setter

自定义 Person 类

class Person: NSObject {

    var name: String?
    var age: Int?
}

getter & setter

var _name: String?

var name: String? {
    get {
        return _name
    }
    set {
        _name = newValue
    }
}

didSet

var length: Int? {
    didSet {
        timeStr = String(format: "%02d:%02d:%02d", arguments: [length! / 3600, (length! % 3600) / 60, length! % 60])
    }
}
var timeStr: String?

计算型属性

var title: String {
    get {
        return "Mr " + (name ?? "")
    }
}
var title: String {
    return "Mr " + (name ?? "")
}

构造函数

init(dict: [NSObject: AnyObject]) {
    name = dict["name"] as? String
    age = dict["age"] as? Int
}

析构函数

deinit {
    print("88")
}

十一. ATS 应用传输安全

App Transport Security (ATS) lets an app add a declaration to its Info.plist file that specifies the domains with which it needs secure communication. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one. <br /><br />If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible.

强制访问

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

设置白名单

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>
上一篇下一篇

猜你喜欢

热点阅读