扩展和语法糖,用于丰富 Swift 标准库、iOS 框架和 SwifterSwift。
pod 'SweeterSwift'
dependencies: [
.package(url: "https://github.com/yonat/SweeterSwift", from: "1.2.6")
]
在视图中心添加按钮
view.addConstrainedSubview(button, constrain: .centerX, .centerY)
将标签放在 textField 上方
view.constrain(label, at: .leading, to: textField)
view.constrain(textField, at: .top, to: label, at: .bottom, diff: 8)
添加子视图控制器,覆盖除底部边距外的所有区域
addConstrainedChild(vc, constrain: .bottomMargin, .top, .left, .right)
应用名称,合理回退到进程名称
let appName = Bundle.main.name
包含名称、版本和构建号的应用信息字符串
let appInfo = Bundle.main.infoString // "MyApp 1.0 #42"
从字典创建对象
let decodableObject = MyDecodableClass(dictionary: aDictionary)
将对象导出到字典
let aDictionary = encodableObject.dictionary
使用格式创建
let dateFormatter = DateFormatter(format: "cccc, MMMM dd")
使用 NotificationCenter.default
发送本地通知
notify(notificationName, userInfo: infoDictionary)
响应来自 NotificationCenter.default
的本地通知
observeNotification(notificationName, selector: #selector(someFunc))
从 HTML 创建
let attributedString = NSAttributedString(htmlString: "Hello, <b>world</b>!")
将子字符串转换为链接
mutableAttributedString.link(anchorText: "Hello", url: "https://ootips.org")
将内容转储到控制台以进行调试
managedObjectContext.printAllObjects()
创建存储的副本,用于备份或稍后用作初始设置
managedObjectContext.backupStore()
将 CamelCase 分隔为首字母大写的单词
let words = "winterIsComing".unCamelCased // "Winter Is Coming"
将 CamelCase 更改为 snake_case 格式
let key = "winterIsComing".camelToSnakeCased // "winter_is_coming"
当前枚举案例在 allCases
中的索引
let index = MyEnum.someCase.index
解包集合,compactMap { $0 }
的简写
let nonOptionals = optionalsCollection.compact
在将成员函数作为 @escaping 闭包传递时避免循环引用
var closure = weak(self, in: MyClass.someFunction)
标准时间间隔
let myInterval: TimeInterval = .year + .month + .week + .day + .hour + .minute
查找最顶层的视图控制器
let topVC = UIApplication.topViewController()
在最顶层视图控制器之上呈现模态视图
UIApplication.present(modalVC)
通过使用 UITextView
自动检测链接并模拟 UILabel
外观来创建带有链接的标签
let hyperlinkedLabel = UITextView(simulatedLabelWithLinksInText: "More at https://ootips.org")
从视图层级中移除一个排列的子视图,而不仅仅是堆栈排列
stackView.removeArrangedSubviewCompletely(subview)
从视图层级中移除所有排列的子视图,而不仅仅是堆栈排列
stackView.removeAllArrangedSubviewsCompletely()
在视图层级中递归搜索满足条件的子视图
let blueSubview = view.viewInHierarchy(where { $0.backgroundColor == .blue })
在视图层级中递归搜索具有特定类的子视图
let button = view.viewWithClass(UIButton.self)