1.多行文字的字符串:
之前我们可以通过使用 “\ n” 来使字符串换行比如:
let beforeString = "When you write a string that spans multiple \nlines make sure you start its content on a \nline all of its own, and end it with three \nquotes also on a line of their own. Multi-line strings also let you write "quote marks" \nfreely inside your strings, which is great!" //print(beforeString)
这种方式阅读起来很不方便,看起来很不美观,不能直观的显示它所要呈现给用户展示的样子。
在swift4.0中,提供了专门的语法来显示多行字符串,从而告别转义:
1)以三个双引号作为开始的标识。
2)以三个双引号作为结束的标识。
3)不管开始标识还是结束标识,都必须单独占据一行
4)你定义的字符串就是开始标识和结束标识中间的样子
let longString =
"""
When you write a string that spans multiple
lines make sure you start its content on a
line all of its own, and end it with three quotes also on a
line of their own. Multi-line strings also let you write "quote marks" freely inside your strings, which is great!
"""
print(longString)
2.改进键值编码的关键字
swift中如何使用的keyPath呢?
首先,我们定义两个结构体:
struct Crew {
var age: String
var height: String
}
struct SuperMen {
var name: String
var age: Double
var height: Crew
func goToMaximumWarp() {
print("\(name) is now travelling at warp \(maxWarp)")
}
}
let janeway = Crew(name:"Kathryn Janeway",rank:"Captain")
let voyager = Starship(name: "Voyager", maxWarp: 9.975, captain: janeway) let enter = voyager.goToMaximumWarp enterWarp()
在swift中,我们可以给函数添加一个引用。比如,我们可以给goToMaximumWarp()方法添加一个叫做enter的引用,之后我们便可以使用enter来调用它。然而,我们却不能对属性做同样的操作。是的,我们不能给SuperMen的名字属性添加一个引用。
这个问题,可以通过使用keypath来解决:正如enter()一样,它们是未被调用的属性引用。如果您现在调用引用,则得到当前值,但如果稍后调用引用,则获得最新值
。keyPath的语法格式为反斜杠:
let nameKeyPath = \SuperMen.name
let maxWarpKeyPath = \SuperMen.age
let captainName = \SuperMen.captain.height
print(voyager[keyPath: nameKeyPath]) //Voyager
voyager[keyPath: nameKeyPath] = "456" print(voyager.name) //456
voyager.goToMaximumWarp() //456 is now travelling at warp 9.975
enterWarp() //Voyager is now travelling at warp 9.975
let starshipName = voyager[keyPath: nameKeyPath]
let starshipMaxWarp = voyager[keyPath: maxWarpKeyPath]
let starshipCaptain = voyager[keyPath: captainName]
3.改进了字典功能:
Swift4.0让词典的功能更强大。
在Swift3.0中,Dictionary的过滤函数会返回一个包含key / value元组的数组。比如
:
let names = ["小明": 24_256_800, "小强": 23_500_000, "笑话": 21_516_000, "Seoul": 9_995_000];
let massiveName = names.filter { $0.value > 10_000_000 }
在Swift3.0中,你不能通过massiveName [ “小明”]来获取对应的值。
因为massiveName不是一个字典类型。只能通过massiveName [0]。价值来获取。
但在Swift4.0中,massiveName是字典类型,使用massiveName [ “小明”]获取值完全没有问题。
4.String又变成了集合类型:
这意味着,你可以做字符串倒置,循环获取每个字符,map,flatMap()等操作。
比如:
let quote = "It is a truth universally acknowledged that new Swift versions bring new features."
let reversed = quote.reversed()
for letter in quote {
print(letter)
}
另外,Swift4.0中,引入类似于python中字符串的一些操作。在省略起始位置或者结束位置的情况下,可以自动推断集合的起始位置或者结束位置。
let person = ["name", "age", "heght", "hand", "foot"]
let big = person[..<3]
let small = person[3...]
print(big) //["name", "age", "height"]
print(small) //["hand", "foot"]