Swift4.0新特性(上)
2017-06-14 本文已影响2632人
Mg明明就是你
The Swift Programming Language (Swift 4)
Swift的180个介绍
Range
//: # 一、更便捷的Range
var str = "Hello, playground"
// Swift3.0
var index = str.index(of: " ")!
let greeting = str[str.startIndex ..< index]
index = str.index(index, offsetBy: 1) // index 下标 +1
let name = str[index ..< str.endIndex]
// Swift4.0
var index1 = str.index(of: " ")!
let greeting1 = str.prefix(upTo: index1)
index1 = str.index(index1, offsetBy: 1)
let name1 = str.suffix(from: index1)
print(Array(str.enumerated()))
print(Array(zip(1..., str)))
截图展示.png
二、Str的变化一个集合类型
-
简介
var str = "Hello, playground"
print(str.characters.count) // Swift3.0写法
print(str.count) // Swift4.0写法
/// 遍历
str.forEach {
$0
}
-
多行文字 (""" """)
/// plist格式
let plistInfo = """
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<array>
<dict>
<key>title</key>
<string>设置WiFi</string>
<key>imageName</key>
<string>serversSet</string>
</dict>
</array>
</plist>
"""
/// JSON格式
let jsonInfo = """
{
"data": {
"title": "String is a collection"
"author": "23"
"creat_at": "2017-06-13"
}
}
"""
print(plistInfo)
print(jsonInfo)
打印结果.png
三、改进的private的访问权限
//: # 改进的private的访问权限(扩展中可以访问private修饰的变量了)
class Person {
fileprivate var name: String = "MG"
private var age = 23
}
extension Person {
func change() {
name = "明明"
age = 32
}
}
let person = Person()
person.change()
截图展示.png
四、更智能安全的Key Value Coding
//: # 更智能安全的Key Value Coding
class Weather: NSObject {
@objc var months = 12
@objc var season = "Spring"
@objc var seasones = ["Spring","Summer","Autumn;","winter"]
}
/// Swift4之前的写法
let w = Weather()
w.season = "Summer"
var season = w.value(forKeyPath: "season")
w.setValue("Autumn", forKeyPath: "season")
/// Swift4.0
let seasonKeyPath = \Weather.season
var season1 = w[keyPath: seasonKeyPath]
w[keyPath: seasonKeyPath] = "MG明明"
截图展示.png
轻轻点击,关注我简书
轻轻点击,关注我简书
轻轻点击,关注我微博
浏览我的GitHub
扫一扫,关注我.jpg
扫一扫,关注我