Reputation: 919
I'd like to be able to extend Double
with a custom conversion to String
, but I would like to limit this only to implementations with classes/structs. For
extension Double {
var customStringOutput: String {
guard self >= 0.0 else { return "Invalid" }
return "My number is: \(self)"
}
}
struct MyStruct {
var myNumber: Double = 100.0
}
let myStruct = MyStruct()
let doubleFail = 99.0
print(myStruct.myNumber.customStringOutput) //"My number is: 100.0"
print(doubleFail.customStringOutput) //"My number is :99.0" - Should fail
I have tried to create a protocol such as:
protocol DoubleCustomStringConvertable { ... }
Applying that to Double
produces the same result as just extending Double directly. I can create a function within my struct that takes the double as a parameter and returns my string which would technically solve my problem, but this is more of a learning exercise and I like the cleaner syntax of the property.
How do I allow the protocol to only apply to Double's within my defined struct? This is probably so simple I will kick myself!
Upvotes: 2
Views: 204
Reputation: 3440
Don't make it a protocol, but rather just a function defined within your structure. There is no way to limit the scope of a protocol (to all Double
s within a value type like MyStruct
).
Upvotes: 1