前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 15 format新方法

iOS 15 format新方法

作者头像
小刀c
发布2022-09-21 16:18:24
4030
发布2022-09-21 16:18:24
举报
文章被收录于专栏:cc logcc log

iOS 15格式化新方式

swift算语法很甜的语言了,但是iOS 15之前个格式化需要先 init 一个formatter,然后再根据配置格式化数据, 稍微有点点麻烦。

从iOS 15(macOS 12,watchOS 8……)开始,我们直接像其他面向对象语言一样,直接在数据上.formatted就好。

iOS 15 Date格式化

代码语言:javascript
复制
let now = Date()
print(now.formatted())
// 2021/7/18, 12:19 AM

print(now.formatted(date: .complete, time: .omitted))
// Sunday, July 18, 2021

需要ISO8601 API?

代码语言:javascript
复制
let now = Date()
print(now.formatted(.iso8601.dateSeparator(.dash)))
// 2021-07-17T161944Z

还有更长的语法

代码语言:javascript
复制
let now = Date()
print(now.formatted(.dateTime.year().month()))
// Jul 2021

print(now.formatted(.dateTime.year(.twoDigits).month(.wide)))
// July 21

.dateTime可以设置更精确的时间,也可以让你设置地区

代码语言:javascript
复制
let now = Date()
print(now.formatted(.dateTime.locale(Locale(identifier: "cs"))))
// 18. 7. 2021 0:19

number格式化

代码语言:javascript
复制
print(40.formatted(.percent))
// 40%

print(40.formatted(.currency(code: "eur")))
// ¥40.00

print(0.2948485.formatted(.number.precision(.significantDigits(2))))
// 0.29

可以使用ByteCountFormatter来格式化文件大小

代码语言:javascript
复制
print(38436483.formatted(.byteCount(style: .file, allowedUnits: .all, spellsOutZero: true, includesExactByteCount: false)))
// 38.4 MB

ListFormatter也能.formatted

ListFormatter 也能在collection中.formatted使用。

代码语言:javascript
复制
let appleStuff = ["iPhone", "iPad", "Mac"]
print(appleStuff.formatted())
// iPhone, iPad, and Mac

更多: What's new in Foundation

New approach to formatters in iOS 15

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • iOS 15格式化新方式
    • iOS 15 Date格式化
      • number格式化
        • ListFormatter也能.formatted
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档