[swift-evolution] Tuples as RawRepresentable
J.E. Schotsman
jeschot at xs4all.nl
Sat Oct 15 15:14:37 CDT 2016
> On 15 Oct 2016, at 19:00, Karl Wagner wrote:
>
> The edge-case I have in mind is... let's say we synthesised RawRep conformance for all Equatable raw-types. That would allow you use struct and class rawvalues with our shorthand syntax.
I am not saying the compiler should do all the work. It’s OK with me if I have to make the rawValue type RawRepresentable myself.
Consider the following code, where Rectangle is a type that is useful on its own:
import Cocoa
struct Rectangle: RawRepresentable
{
var width: Int = 0
var height: Int = 0
}
extension Rectangle: RawRepresentable
{
typealias RawValue = String
init( rawValue:String )
{
let values = rawValue.componentsSeparatedByString("x")
if let width = Int(values[0]), let height = Int(values[1]) { self.init( width:width, height:height ) }
else { self.init( width:0, height:0 ) }
}
var rawValue:String { return "\(width)x\(height)" }
}
enum RectFormat: Rectangle
{
case SMALL = “30x30"
case MEDIUM = “60x60"
case LARGE = “120x120"
var width: Int { return rawValue.width }
var height: Int { return rawValue.height }
}
let fmt = RectFormat.MEDIUM
print ("width: \(fmt.width) height: \(fmt.height)")
This was written in Xcode and Swift 2.2 (I cannot yet update to Swift 3) and does not compile.
Given this Rectangle struct I would like to be able to write
enum RectFormat: Rectangle
{
case SMALL = Rectangle (30,30)
case MEDIUM = Rectangle (60,60)
case LARGE = Rectangle (120,120)
}
let fmt = RectFormat.MEDIUM
print ("width: \(fmt.width) height: \(fmt.height)”)
let fmt2 = RectFormat( rawValue:Rectangle (40,40) ) // fmt2 is nil
IOW no need for literals, no need to copy the properties or methods of Rectangle, omit rawValue when accessing them.
If the compiler needs to store the cases as literals we can require RawValue to be StringLiteralType, IntegerLiteralType or FloatLiteralType (or a tuple of these).
IMHO the developer can take on the responsibility for making sure the mapping from and to RawValue is one to one.
I am not sure if this is purely additive sugar (might be, except in case of tuples?).
Jan E.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161015/156c0896/attachment.html>
More information about the swift-evolution
mailing list