DJohnson DJohnson - 6 months ago 11
Swift Question

Extend Double only within my struct

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!

Answer

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).