[英]How can I as generically as possible grab all text from the frontmost window/document on OSX?
[英]How can I define `unlines` function generically?
我想定義一個unlines
function,它適用於任何其元素符合 StringProtocol 的序列; 這是我的嘗試:
func unlines<S: StringProtocol>(_ xs: Sequence<S>) -> S {
return xs.joined(separator: "\n")
}
錯誤:使用協議“序列”作為類型必須寫成“任何序列”
為具體類型定義的版本確實有效:
func unlines(_ xs: [String]) -> String {
return xs.joined(separator: "\n")
}
但只能應用於字符串列表。
我如何制定一個通用定義?
編輯:
例如,我想將它應用於以下值:
["Hello", "World"].lazy.map { $0.lowercased() }
joined
返回一個 String,因此您需要更改返回類型並使用any Sequence
func unlines<S: StringProtocol>(_ xs: any Sequence<S>) -> String {
return xs.joined(separator: "\n")
}
這然后適用於 String 和 Substring
字符串示例:
let result = unlines(["A", "B", "C"])
Substring 示例:
let result = unlines("A-B-C".split(separator: "-"))
都返回
一種
乙
C
在 Swift 中,您通常會使用協議擴展來定義應在實例上運行的實例函數,而不是使用采用第一個參數的自由函數。
這可能是這樣工作的:
extension Sequence where Element: StringProtocol {
// FIXME: This is a pretty Haskelly, non-Swifty name
func unlines() -> String {
joined(separator: "\n")
}
}
let input = ["Hello", "World"]
.lazy
.map { $0.lowercased() }
.unlines()
print(input)
// Prints:
// hello
// world
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.