Can you create polyfills in swift using availability checking? -
swift 2 lets check current platform , version make sure newer methods/properties available , allow write fallback code if not, writing conditional block #available
.
so example, in osx10.10, nstextfield
has property called placeholderstring
, in older versions, had access info via intermediate nstextfieldcell
object. safely use new system fallback old 1 this:
var placeholder : string if #available(osx 10.10, *) { placeholder = inputbox.placeholderstring! } else { placeholder = (inputbox.cell as! nstextfieldcell).placeholderstring! }
swift allows extend existing classes extension
for example, adding placeholder property nstextfield
extension nstextfield { var placeholderstring: string? { return (self.cell as! nstextfieldcell).placeholderstring } }
so... possible combine these 2 ideas , create polyfill, extend class conditionally on current platform, in order retrospectively add features of new api older platforms?
so in example, want write this:
if !#available(osx 10.10, *) { extension nstextfield { var placeholderstring: string? { return (self.cell as! nstextfieldcell).placeholderstring } } }
the above doesn't compile. illustrates kind of thing i'm looking for. if particular thing available on current platform, use it, otherwise supply implementation it.
is there way in swift achieve this?
subsequently able safely use textfield.placeholderstring
without needing worry platform version.
if #available()
checked runtime, not @ compile or link time. therefore assume possible way define wrapper method:
extension nstextfield { var myplaceholderstring: string? { if #available(osx 10.10, *) { return self.placeholderstring } else { return (self.cell as! nstextfieldcell).placeholderstring } } }
(and understand not looking for.) perhaps else has better solution!
Comments
Post a Comment