一些代码,
typealias Brio = (String, String, String)
extension Brio {
static var divider: Brio {
return ("_", "_", "_")
}
static var isDivider: Bool {
return (self.0 == "_")
}
}
元组扩展必须写为“(重复每个元素)”的扩展,
元组扩展必须声明符合一个协议
元组扩展是实验性的
我真的无法从这个聊天中弄清楚,
https://forums.swift.org/t/pitch-user-define-tuple-conformances/67154
我不明白以下内容,但如果相关的话:
fattie@m2max203mbp16 ~ % swift --version
swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0
fattie@m2max203mbp16 ~ %
这是一个扩展元组的示例
// Setup the screen selector button
screensButton.showsMenuAsPrimaryAction = true
let noms = [
Brio("CA", "Cats", "cat.fill"),
Brio("DO", "Dogs", "fido.circle"),
Brio("DO", "Horsies", "equine.circle"),
.divider,
Brio("DEV", "Dev reload", "link"),
Brio("DX", "Dev, clear", "circle"),
.divider,
Brio("XX", "Example", "circle.dotted"),
Brio("XX", "Example", "link"),
]
var elements = noms.chompchomp(){ k in self.screensButtonProcess(k) }
screensButton.menu = UIMenu(children: elements)
必须使用类很烦人。使用元组会更纯粹,例如,
let noms = [
("CA", "Cats", "cat.fill"),
("DO", "Dogs", "fido.circle"),
("DO", "Horsies", "equine.circle"),
.divider,
("DEV", "Dev reload", "link"),
脚注,这是
chompchomp
的代码,作为一个类Brio
而不是元组含泪完成:
///A "BUTTON TRIO". Internal code, title, image. Use a `[Brio]` to make menus. Just put `.divider` where you want dividers.
struct Brio {
let c: String
let t: String
let i: String
var isDivider: Bool = false
}
extension Brio {
init(_ x: String, _ y: String, _ z: String) {
self.init(c: x, t: y, i: z)
}
///When you type-out a `Brio` array just put `.divider` where you want dividers.
static var divider: Brio {
return Brio(c: "_", t: "_", i: "_", isDivider: true)
}
}
extension [Brio] {
///Chew on an array of `Brio` and spit out the UIMenuElement array. Recall that to create dividers in UIKit menus, basically each run (other than the first) is marked as inline.
func chompchomp(with: @escaping (_ tapped: String)-> ()) -> [UIMenuElement] {
var brios = self
var result = brios.chomp().elements{ b in with(b) }
var run = brios.chomp().elements(with: { b in with(b) })
while !run.isEmpty {
result.append(UIMenu(options: .displayInline, children: run))
run = brios.chomp().elements(with: { b in with(b) })
}
return result
}
///Simply give the next run of menu items removing that run.
mutating func chomp() -> [Brio] {
let spl = self.split(maxSplits: 1, whereSeparator: { $0.isDivider })
self = (spl.count < 2) ? [] : Array(spl[1])
return (spl.count < 1) ? [] : Array(spl[0])
}
///Alchemize one run of Brio into an array of UIMenuElement.
func elements(with: @escaping (_ tapped: String)-> ()) -> [UIMenuElement] {
return self.map({ brio in
return UIAction(title: brio.t, image: UIImage(systemName: brio.i)) { _ in
with(brio.c)
}
})
}
}
首先,我会考虑将 Brio 作为一个真正的类,而不是构造并使用扩展中实现的函数作为类中的方法。在这种情况下真的有必要使用元组吗?让我知道。