#1.添加Codable協(xié)議彪标,方便自定義數(shù)據(jù)類型序列化
#2.添加定義多行字符串語法
#3.改進(jìn)key-value coding的keypath
#4.修改并強(qiáng)化字典功能
#5.字符串變?yōu)榧项愋?/p>
1.Swifty encoding and decoding:
在Objective-C中值類型的相互影響是十分糟糕的。比如NSCoding協(xié)議野来,類繼承它之后,我們需要在類中重寫自定義的 encoding 和 decoding方法。這樣顯得十分痛苦而且很容易出錯(cuò)。
在swift4.0 中蹬癌,引入了新的Codable協(xié)議,可以讓你在不添加其他特殊代碼的情況下序列化和反序列化自定義的數(shù)據(jù)類型虹茶,從而不用擔(dān)心值類型的丟失逝薪。更漂亮的是,你可以選擇數(shù)據(jù)被序列化為什么樣的格式:plist(XML)或者JSON蝴罪。
是的董济,Swift 4 可以讓你在不添加任何特殊代碼的情況下將自定義數(shù)據(jù)類型序列化為JSON。
以代碼為例:
首先要门,我們自定義一個(gè)數(shù)據(jù)類型:
struct Language:Codable {
var name: String
var version: Int
}
let swift = Language(name:"Swift",version:4)
let php = Language(name:"PHP",version:7)
let perl = Language(name:"Perl",version:6)
讓Language這個(gè)結(jié)構(gòu)體遵從Codable協(xié)議虏肾,我們便可以將它轉(zhuǎn)化為json格式的數(shù)據(jù)展示:
let encoder = JSONEncoder()
let encoded = try? encoder.encode(swift){
//...
}
Swift將會(huì)自動(dòng)編碼你的數(shù)據(jù)類型中的所有屬性。
我們可以使用encode和decode方法來編碼和解碼對(duì)象:
let encoder = JSONEncoder()
let encoded = try? encoder.encode(swift)
if encoded != nil {
if let json = String(data: encoded!,encoding:.utf8){
print(json)
}
}
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Language.self, from: encoded!)
{
print(decoded.name)
}
同樣可以有PropertyList的encode和decode:
//PropertyList
let propertyListEncoder = PropertyListEncoder()
let propertyListed = try? propertyListEncoder.encode(php)
let propertyDecoder = PropertyListDecoder()
if let value = try? propertyDecoder.decode(Language.self,from: propertyListed!)
{
print(value.name)
}
了解更多關(guān)于swift4.0 encode和decode的內(nèi)容欢搜,可以參考鏈接:the Swift Evolution proposal for this new feature
2.多行文字的字符串:
之前我們可以通過使用"\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)
這種方式閱讀起來很不方便,看起來很不美觀炒瘟,不能直觀的顯示它所要呈現(xiàn)給用戶展示的樣子吹埠。
在swift4.0中,提供了專門的語法來顯示多行字符串疮装,從而告別轉(zhuǎn)義缘琅。
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)
語法說明:
1.以三個(gè)雙引號(hào)作為開始的標(biāo)識(shí)。
2.以三個(gè)雙引號(hào)作為結(jié)束的標(biāo)識(shí)廓推。
3.不管開始標(biāo)識(shí)還是結(jié)束標(biāo)識(shí)刷袍,都必須單獨(dú)占據(jù)一行
4.你定義的字符串就是開始標(biāo)識(shí)和結(jié)束標(biāo)識(shí)中間的樣子
了解更多可以參考鏈接:the Swift Evolution proposal for this new feature.
3.改進(jìn)key-value coding的keypath
Swift中如何使用keypath呢?
首先樊展,我們定義兩個(gè)結(jié)構(gòu)體:
struct Crew {
var name: String
var rank:String
}
struct Starship {
var name: String
var maxWarp: Double
var captain: Crew
func goToMaximumWarp(){
print("\(name) is now travelling at warp \(maxWarp)")
}
}
let janeway = Crew(name:"Kathryn Janeway",rank:"Captain")
var voyager = Starship(name: "Voyager", maxWarp: 9.975, captain: janeway)
let enterWarp = voyager.goToMaximumWarp
enterWarp()
在Swift中呻纹,我們可以給函數(shù)添加一個(gè)引用。比如专缠,我們可以給goToMaximumWarp()方法添加一個(gè)叫做enterWarp的引用雷酪,之后我們便可以使用enterWarp來調(diào)用它。然而藤肢,我們卻不能對(duì)屬性做同樣的操作太闺。是的糯景,我們不能給Starship的name屬性添加一個(gè)引用嘁圈。
這個(gè)問題省骂,可以通過使用keypath來解決:正如enterWarp()一樣,它們是未被調(diào)用的屬性引用最住。 如果您現(xiàn)在調(diào)用引用钞澳,則得到當(dāng)前值,但如果稍后調(diào)用引用涨缚,則獲得最新值轧粟。
keyPath的語法格式為反斜杠:
let nameKeyPath = \Starship.name
let maxWarpKeyPath = \Starship.maxWarp
let captainName = \Starship.captain.name
之后你便可以在Starship的實(shí)例中使用它了:
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]
想要了解更多,可以參考鏈接:the Swift Evolution proposal for this new feature
4.改進(jìn)了字典功能:
Swift4.0 讓Dictionary的功能更強(qiáng)大脓魏。
在Swift3.0 中兰吟,Dictionary的filter函數(shù)會(huì)返回一個(gè)包含key/value元組的數(shù)組。
比如:
let cities = ["Shanghai": 24_256_800, "Karachi": 23_500_000, "Beijing": 21_516_000, "Seoul": 9_995_000];
let massiveCities = cities.filter { $0.value > 10_000_000 }
在Swift3.0中茂翔,你不能通過massiveCities["Shanghai"]來獲取對(duì)應(yīng)的值混蔼。因?yàn)閙assiveCities不是一個(gè)字典類型。只能通過massiveCities[0].value來獲取珊燎。
但在Swift4.0中惭嚣,massiveCities是字典類型,使用massiveCities["Shanghai"]獲取值完全沒有問題悔政。
print(massiveCities["Shanghai"] ?? "nil Value");
想要了解更多晚吞,可以參考鏈接:the Swift Evolution proposal for these new features.
5.String 又變成了集合類型:
這意味著,你可以做字符串倒置谋国,循環(huán)獲取每個(gè)字符槽地,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中字符串的一些操作旅急。在省略起始位置或者結(jié)束位置的情況下逢勾,可以自動(dòng)推斷集合的起始位置或者結(jié)束位置。
let characters = ["Dr Horrible", "Captain Hammer", "Penny", "Bad Horse", "Moist"]
let bigParts = characters[..<3]
let smallParts = characters[3...]
print(bigParts) //["Dr Horrible", "Captain Hammer", "Penny"]
print(smallParts) //["Bad Horse", "Moist"]
想要了解更多藐吮,可以參考鏈接:the Swift Evolution proposal for this new feature.