讓我們深入探討“字符串插值(StringInterpolation)”答恶,一個(gè) Swift 5 里很酷的特性囊榜。
在“字符串插值”的幫助下,我們可以定義在打印對(duì)象時(shí)該對(duì)象在字符串中的顯示方式(在使用 print 函數(shù)或使用 po
調(diào)試命令時(shí))亥宿。
當(dāng)我們打印 Struct 時(shí)卸勺,將會(huì)輸出結(jié)構(gòu)體名稱,然后是其所有屬性烫扼。代碼如下:
struct AppUser{
var firstName: String
var lastName: String
}
let appUser = AppUser(firstName : "Payal", lastName : "Maniyar")
print("User details: \(appUser)")
// 輸出:
User details: AppUser(firstName: "Payal", lastName: "Maniyar")
但是如果我們想打印類對(duì)象曙求,那么行為與 Struct 不同了。代碼片段如下:
class Point {
let x: Int, y: Int
init( x: Int, y: Int){
self.x = x
self.y = y
}
}
let p = Point(x: 21, y: 30)
print(p)
// 輸出:
__lldb_expr_11.Point
要像 Struct 那樣打印類對(duì)象映企,需要用到 CustomStringConvertible
協(xié)議悟狱,來看看這段代碼里的用法:
class Point {
let x: Int, y: Int
init( x: Int, y: Int){
self.x = x
self.y = y
}
}
let p = Point(x: 21, y: 30)
print(p)
extension Point: CustomStringConvertible {
var description: String {
return "Point : (\(x), \(y))"
}
}
// 輸出:
Point : (21, 30)
如果使用 CustomStringConvertible
,則可以實(shí)現(xiàn) description
屬性來打印對(duì)象堰氓。
通過字符串插值還可以使用不同的參數(shù)和結(jié)果來打印對(duì)象挤渐。來理解一下這段代碼:
class User {
var firstName: String
var lastName: String
init (firstName: String,lastName: String){
self.firstName = firstName
self.lastName = lastName
}
}
//StringInterpolation 1
extension String.StringInterpolation{
mutating func appendInterpolation(_ user: User) {
appendInterpolation("My name is : \(user.firstName) \(user.lastName)")
}
}
//StringInterpolation 2
extension String.StringInterpolation{
mutating func appendInterpolation(_ firstName: String,_ lastName: String) {
appendInterpolation("First Name : \(firstName) Last Name : \(lastName)")
}
}
let user = User(firstName : "Payal ", lastName : "Maniyar")
print("User details: \(user.firstName,user.lastName)")// This will use StringInterpolation 2
print("User details: \(user)")// This will use StringInterpolation 1
// 輸出為:
User details: First Name : Payal Last Name : Maniyar
User details: My name is : Payal Maniyar
在上面的代碼中,通過參數(shù)可以選擇哪一個(gè) StringInterpolation
擴(kuò)展被使用双絮。
繼續(xù)來使用更高級(jí)的用法……
你的自定義插值方法可以根據(jù)需要獲取任意多的參數(shù)浴麻,無論是否帶標(biāo)簽得问。例如,我們可以使用各種樣式添加插值以打印數(shù)字软免,如下所示:
import Foundation
extension String.StringInterpolation {
mutating func appendInterpolation(_ number: Int, style: NumberFormatter.Style) {
let formatter = NumberFormatter()
formatter.numberStyle = style
if let result = formatter.string(from: number as NSNumber) {
appendLiteral(result)
}
}
}
let number = Int.random(in: 0...100)
let lucky1 = "The lucky number this week is \(number, style: .ordinal)."
print(lucky1)
// 輸出為:
The lucky number this week is 100th.
你可以根據(jù)需要多次調(diào)用 appendLiteral()
宫纬,也可以根本不調(diào)用。例如膏萧,我們可以添加一個(gè)字符串插值來多次重復(fù)一個(gè)字符串:
extension String.StringInterpolation {
mutating func appendInterpolation(repeat str: String, _ count: Int) {
for _ in 0 ..< count {
appendLiteral(str)
}
}
}
print("\(repeat: "Do what you like\n ", 6)")
// 輸出:
Do what you like
Do what you like
Do what you like
Do what you like
Do what you like
Do what you like
而且漓骚,由于這些只是常規(guī)方法,你可以使用 Swift 的全部功能榛泛。例如蝌蹂,我們可能會(huì)添加一個(gè)將字符串?dāng)?shù)組連接起來的插值,但若這個(gè)數(shù)組為空曹锨,則執(zhí)行另一個(gè)返回字符串的閉包:
extension String.StringInterpolation {
mutating func appendInterpolation(_ values: [String], empty defaultValue: @autoclosure () -> String) {
if values.count == 0 {
appendLiteral(defaultValue())
} else {
appendLiteral(values.joined(separator: ", "))
}
}
}
func EmptyMsg () -> String {
return "No one found"
}
var names = ["Harry", "Ron", "Hermione"]
print("List of students: \(names, empty: EmptyMsg()).")
names.removeAll()
print("List of students: \(names, empty: EmptyMsg() ).")
// 輸出:
List of students: Harry, Ron, Hermione.
List of students: No one found.
就是這樣……
希望現(xiàn)在你已經(jīng)清楚 StringInterpolation
的用法了叉信。
原文: https://medium.com/@payalmaniyar/swift-5-understanding-of-string-interpolation-cdc8bb622ce3
作者:Payal Maniyar
編譯:碼王爺