swift : merge the same processing code by prop type, not by prop name?
If I understood correctly, you don't want to merge, you want to factorize...
So:
struct InfoFormatting {
static func infos(from text: String, andNumber number: Int) -> String {
var result = "\(number) "
if number > 1 {
result += "number"
}
else {
result += "number"
}
return result + " in \(text)"
}
}
I've created InfoFormatting
, but it could be elsewhere, it depends on your architecture on where it would make more sense.
Then:
struct GroupA {
...
var info: String {
InfoFormatting.infos(from: name, andNumber: memberNum)
}
}
struct GroupA {
...
var info: String {
InfoFormatting.infos(from: title, andNumber: peopleCount)
}
}
That is the basic factorization.
Now, you could also use instead a protocol:
protocol InfoFormatter {
var infos: String { get }
}
extension InfoFormatter {
func infos(from text: String, andNumber number: Int) -> String {
var result = "\(number) "
if number > 1 {
result += "number"
}
else {
result += "number"
}
return result + " in \(text)"
}
}
And make GroupA
& GroupB
compliant with it:
struct GroupA: InfoFormatter {
let name: String
let memberNum: Int
var info: String {
infos(from: name, andNumber: memberNum)
}
}
struct GroupB: InfoFormatter {
let title: String
let peopleCount: Int
var info: String {
infos(from: title, andNumber: peopleCount)
}
}