[swift-evolution] struct finalization constraint for protocols

Andrey Volodin siddok at gmail.com
Thu Apr 13 04:25:47 CDT 2017

Hello everyone!

First of all, I know swift goes into a bit different direction for super type safety, but the problem that is going to describe is kind of common to anybody who use general purpose library (that are not bound to any big UI/non-UI framework).

I’m a game-engine and deep learning developer and I use Swift on the daily basis. The thing I think that Swift really misses is struct protocols. Here is the basic example. 

Imagine you do a game with some sort of game engine. That game engine is based on some math lib and you store all vector data (i.e. positions etc) in the something like Point2D from that lib. And then you decided that you need to draw a complex polygons in your game. So you search for a triangulation lib. And you find it, but it uses its own format to describe points, say Triangulation.Point. The thing is that you have a huge buffer of points to triangulate, but you need to map every single one of them to that new format of that lib and than convert it back. 

Wouldn’t it be nice if we could invent a way to globalize types like that? 

Imagine you declare something like this in your imaginary triangulation library:

final public protocol Vector2D { // or the syntax could be `Vector2D: struct`
    var x: Double { get set }
    var y: Double { get set }

And base the algorithm on this one. So you tell the compiler that we will operate on the structs with a known and final layout. Then in your application you only need to do:

public extension Point2D: Vector2D {}

Types that will conform to such protocols will have some very strict constraints. For example they will have to have the same memory layout (i.e. no protocol variables), stored properties in extensions (that are coming soon) will be also forbidden for such types. The goal is to decrease the need of converting data when you don’t really have to. Those types will have to have the same properties, in the same order, all of them must be stored ones.

For example we have a bunch of C libs like OpenCV or dlib and every one of them has its own image format. Every single one has own its pixel struct and you always need to convert between them. 

I personally think that having something like «type globalization» can improve language ecosystem overall and make things more cross-platform. You can think of it as a typealiasing but without knowing a type you are aliasing to. The compiler will just merge all those types into one during compilation.

Once again: I know this is kind of arguable thing, I just wanted to know your opinion on that.

Thanks for your attention,
Andrey Volodin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170413/3006e37d/attachment.html>

More information about the swift-evolution mailing list