Swift之字符串处理
data
和string
互转:1
2
3
4// data转string
let string = String(data:data,encoding:.utf8)
// string转data
let data = myString.data(using:.utf8)json数据中的日期格式处理
json数据中的日期格式有时不是我们想要的,可以使用
encoder.dateEncodingStrategy
来设置不同的时间格式来满足需要:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34struct StudentTime: Codable {
let registerTime: Date
enum CodingKeys: String, CodingKey {
case registerTime = "register_time"
}
}
let stu = StudentTime(registerTime: Date())
encoder.outputFormatting = .prettyPrinted
var encodedData = try encoder.encode(stu)
print(String(data: encodedData, encoding: .utf8)!)
encoder.dateEncodingStrategy = .iso8601
encodedData = try encoder.encode(stu)
print(String(data: encodedData, encoding: .utf8)!)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
encoder.dateEncodingStrategy = .formatted(formatter)
encodedData = try encoder.encode(stu)
print(String(data: encodedData, encoding: .utf8)!)
//打印结果:
{
"register_time" : 573010087.00337005
}
{
"register_time" : "2019-02-28T01:28:07Z"
}
{
"register_time" : "2019-02-28"
}有时服务器返回一个base64编码的数据时,可以设置decoder的
dataDecodingStrategy
属性为base64来得到原始数据:1
2
3
4
5
6
7
8
9
10
11
12
13
14struct Student: Codable {
let blog: Data
}
let res = """
{
"blog": "aHR0cDovL3d3dy5qaWFuc2h1LmNvbS91c2Vycy8zMjhmNWY5ZDBiNTgvdGltZWxpbmU="
}
"""
let json = res.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
let stu = try! decoder.decode(Student.self, from: json)
print(String(data: stu.blog, encoding: .utf8)!)截取字符串
1
2
3
4let wholeString = "北京大龄未婚女青年受过高等教育的比例81.1%,大龄未婚男中一半以上初中未毕业。"
let range = NSRange(location: 2, length: 13)
let rangeString = (wholeString as NSString).substring(with: range)
print(rangeString)