Swift 4 - 解码期间将字符串转换为大写字母
Swift 4 - String Conversion to Capital Case During Decoding
在用Swift 4解码JSON时,我想在解码过程中将字符串转换为大写。 JSON 将其存储为大写
例如
let title = "I CANT STAND THE RAIN"
print(title.capitalized)
如何在解码过程中执行此操作,以便字符串在我的模型中以大写形式存储?
唯一需要注意的是,我只想将 JSON(标题)中的一个属性大写,而不是其余属性。
struct Book: Decodable {
let title: String
let author: String
let genre: String
init(newTitle: String, newAuthor: String, newGenre: String) {
title = newTitle
author = newAuthor
genre = newGenre
}
}
let book = try! decoder.decode(Book.self, from: jsonData)
jsonString.replace(/"\s*:\s*"[^"]/g, match => {
return match.slice(0, -1) + match[match.length - 1].toUpperCase()
})
您可以为您的结构提供您自己的自定义 Decodable 初始值设定项。
struct Book: Decodable {
let title: String
let author: String
let genre: String
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decode(String.self, forKey: .title).capitalized
author = try values.decode(String.self, forKey: .author)
genre = try values.decode(String.self, forKey: .genre)
}
enum CodingKeys: String, CodingKey {
case title, author, genre
}
}
在用Swift 4解码JSON时,我想在解码过程中将字符串转换为大写。 JSON 将其存储为大写
例如
let title = "I CANT STAND THE RAIN"
print(title.capitalized)
如何在解码过程中执行此操作,以便字符串在我的模型中以大写形式存储?
唯一需要注意的是,我只想将 JSON(标题)中的一个属性大写,而不是其余属性。
struct Book: Decodable {
let title: String
let author: String
let genre: String
init(newTitle: String, newAuthor: String, newGenre: String) {
title = newTitle
author = newAuthor
genre = newGenre
}
}
let book = try! decoder.decode(Book.self, from: jsonData)
jsonString.replace(/"\s*:\s*"[^"]/g, match => {
return match.slice(0, -1) + match[match.length - 1].toUpperCase()
})
您可以为您的结构提供您自己的自定义 Decodable 初始值设定项。
struct Book: Decodable {
let title: String
let author: String
let genre: String
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decode(String.self, forKey: .title).capitalized
author = try values.decode(String.self, forKey: .author)
genre = try values.decode(String.self, forKey: .genre)
}
enum CodingKeys: String, CodingKey {
case title, author, genre
}
}