DJohnson DJohnson - 7 months ago 17
Swift Question

Extend Double only within my struct

I'd like to be able to extend

with a custom conversion to
, 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
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!


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 Doubles within a value type like MyStruct).