10 ms·
Swift Generics Evolution
- iddan 8y agoSwift is so awesome! If it was simpler to start a non-UI project and compile time was shorter I would have definitely joined onboard.
- skohan 8y ago> If it was simpler to start a non-UI project You can do it in one command: $ swift package init --type executable
- zapzupnz 8y agoAnd then to make that project openable in Xcode: $ swift package generate-xcodeproj
- tokyodude 8y agowhat makes it awesome? reading the spec nothing sticks out. I often wonder if it's just ObjC survivor bias but if there is anything that makes it actually special I'd love to know.
- saagarjha 8y agoIt has (IMO) pretty and consistent syntax for many programming paradigms. Most of the language decisions seem like they were given significant thought. Swift is a great language to read and write because it strives to be pleasant for both cases.
- nicoburns 8y ago> I often wonder if it's just ObjC survivor bias but if there is anything that makes it actually special I'd love to know. It's definitely not just this. Swift is very similar in design to Rust, and has a lot of the same goodies like an ML-inspired type system, but without the complications imposed by the borrow checker / lack of GC.
- omeid2 8y agoLight syntax, algebraic datatypes, type parameters, very solid enumeration, the whole ObjC library ecosystem, semi-decent (compared to Haskell/OCaml et. al) pattern matching, immutable and mutable data structures (Array vs ArraySlice for example).
- skohan 8y agoDon't forget the whole C library ecosystem, which IMO is much more useful.
- saagarjha 8y agoThis can be somewhat annoying to work with in Swift, though it’s gotten better recently.
- skohan 8y agoIt's not perfect, but it's loads better than using something like JNI.
- saagarjha 8y agoYeah, I can see it being a whole lot worse ;)
- pjmlp 8y agoJNI was made that way on purpose, because Sun wanted to discourage native code, as Mark Reinhold already mentioned a few times on Java conferences. Panama will thankfully fix that. https://jdk.java.net/panama/ https://jdk.java.net/panama/ Just don't expect it to ever be supported on Android. But they surely will, https://en.wikipedia.org/wiki/List_of_Java_virtual_machines#Proprietary_implementations https://en.wikipedia.org/wiki/List_of_Java_virtual_machines#...
- twic 8y agoIt's a decent language, if nothing particularly special. It's like a slightly fresher Java or C#. Survivor bias and standard-issue Apple fanboyism give it some extra shine.
- the_duke 8y agoSwift is a really cool language. Quite similar to Rust, but easier to use. ( GC, no borrow checker, no multi-threading safeguards, ...) I just wish cross platform support was a real priority. The Ubuntu packages are all there is, and much of the ecosystem is centered around (Mac/i)OS.
- pjmlp 8y agoKotlin/Native might turn out to be that, but it depends pretty much where JetBrains is willing to take it. In any case, as rule of thumb, systems languages that come with an OS/platform usually win in the long run.
- jfk13 8y agoI don't really see how "quite similar to Rust" and "GC, no borrow checker, no multi-threading safeguards" can both be true at the same time.
- omeid2 8y agoThey're both highly influenced by ML family of languages.
- skohan 8y agoThey both have similar goals as far as mitigating certain classes of runtime errors through static checks. Both have nice type systems, and features like explicit mutability and nullability. Like you say the approach is pretty different: when it comes to the tradeoff between safety/performance and developer ergonomics Rust leans toward the former where Swift leans toward the latter.
- 0815test 8y agoIt's quite similar to Rust... if Rust literally used Arc<Mutex<T>> everywhere. And Arc<Mutex<T>> everywhere might actually have lower throughput than tracing GC! (Though it's arguably preferable for low-latency code, so it might make some sense for the typical use cases of ObjC and Swift.)
- tambourine_man 8y agoWhenever possible, I like using tech that I can mostly understand. A small simple language is something Swift is not.
- saagarjha 8y agoSwift aims to be useful even if you don't understand parts of it by the principle of progressive disclosure.
- duncanawoods 8y agoHardly. Trying to read someone else’s code is “smack you in the face with a book” disclosure. Go/C# pose no issue but things like c++ cause total wtf where other people’s taste/habits become mutually unintelligible dialects.
- ken 8y agoAnd that is an interesting experiment and perhaps a worthy goal, but having used Swift for a few years now, I don't think they succeeded at this. I'd say it demonstrated that "progressive disclosure" may be a great concept for games, or apps, but there's just way too much difference between someone new to programming and a professional programmer for a language to cover all these cases. Apple doesn't even have a non-pro Final Cut any more. Even in my first few days, having read Apple's Swift documentation, I had to continuously resort to StackOverflow for answers, which frequently sent me to the language grammar (which had many mistakes in it, and I think still does), and the Swift bug tracker. The inflection point on the learning curve is right after "hello world", which makes for great demos, but that's it. Personally, I think even Common Lisp does a better job at progressive disclosure. There's huge areas of CL that you can simply ignore. I worked in CL for years before I bothered to learn about conditions, special variables, or 90% of LOOP's features. In Swift, almost right away I had to read everything related to errors. You can't ignore it, except in the simplest program. I studied generics in college, as part of my data structures class, or maybe my compilers class. I've watched Alexis Gallagher's "PATs" video at least 3 or 4 times. I still don't understand Swift generics. Or maybe I understand what tools are provided, but I don't understand why you'd build (or want) a tool that makes it so hard to, say, define a new type with an "isEqual" method to determine if it's the same as another. Every Swift programmer hits the "protocol can only be used as a generic constraint" phase pretty quick. My complaint with Swift generics was never that they're too simple. It would be great if this were just a corner that PL/type-system geeks could geek out on, but it's an area that you can't ignore.
- TazeTSchnitzel 8y agoIs this describing something similar to how Haskell's return types work?
- r-w 8y agoHow so? I know Haskell has pretty extensive type inference, but I’m not sure exactly how it relates here.
- bsaul 8y agoI haven’t followed C# for a long time, but i remember the type system beeing both obvious and powerful. Could anyone here explain what is swift trying to accomplish here that just copying the C# way wouldn’t be enough ?
- _old_dude_ 8y agoI see two use cases, Swift is a precompiled language unlike C# or Java so a call to a method through a protocol (an interface) can not be inlined. Let suppose you have an interface IList and an IEnumerator, interface IList<T> { IEnumerable<T> iterator(); } it means that despite the fact that you may know the exact implementation of the IList, you have no idea of the exact type of the method iterator() at compile time because it's hidden behind an interface. Enter the existential types, interface IList<T> { type IEnumerator<T> Iterator; // this is a type declaration Iterator iterator(); } now if you have an implementation of IList, you will have class FunnyList<T>: IList<T> { type FunnyListEnumerator<T> Iterator; Iterator iterator(); } so at compile time, when you use a FunnyList, the compiler knows the exact type of the method iterator(). The other usual use case, which is a restricted version, is to be able to specified the variance at use site, like the wildcards in Java (List<? extends Foo>) which is a way to specify that you don't want a method to be parameterized but you want a type of a parameter to be covariant void foo<T:Foo>(List<T> list) // the method is parameterized void foo(List<some Foo> list) // the type is parameterized C# doesn't have variance at use site, only at definition site with 'in' and 'out', Kotlin has both. Scala and C++ with type name form.
- pjmlp 8y agoC# and Java also have AOT compilers available. In fact that is their execution model in UWP, Unity (Consoles, iOS, Xamarin (iOS), Android and some embedded deployments.
- comex 8y agoI've always thought of Swift as a sort of "sister language" to Rust, since so many features have almost the same semantics and syntax, but with some keyword names switched around and slightly different punctuation. These proposed changes continue in that vein :) - As the post notes, `any Shape` is the same as Rust's `dyn Shape` - both languages originally allowed you to write simply `Shape` (i.e. a trait/protocol name) to get an existential type, but later decided that was confusing. - `some Shape` is the same as Rust's `impl Shape`. - `Shape<.Renderer == T>` is equivalent to Rust's `Shape<Renderer=T>`. (This is not meant as a criticism of Swift; Rust has copied some things from Swift as well. Just interesting to note.)
- saagarjha 8y agoYou may have noticed that Swift’s keywords have the same length as Rust’s. This isn’t an accident, apparently: https://twitter.com/jckarter/status/1115343308782358528 https://twitter.com/jckarter/status/1115343308782358528
- twic 8y agoIs `some Shape` actually the same as `impl Shape`? In Rust, `impl Shape` means "a fixed, statically knowable type which implements Shape, and which the implementation of this function knows but its callers do not". I get the impression that in Swift it means "one of the possible numerous which implements Shape, chosen at runtime by the implementation, and returned to the caller as an existential". I may have misunderstood what is planned for Swift though.
- Lukasa 8y ago`some Shape` is literally identical to `impl Shape`, including the semantics you discuss above. The compile-time return value of a function returning `some Shape` must be the same on all execution paths. It just avoids expressing to the caller what it is. Incidentally, this in principle allows the optimiser to specialise the caller to the return type of this function, avoiding the existential altogether.
- skohan 8y agoI believe that's incorrect. Swift generics deal with statically-knowable types. My reading was: `some` -> Some specific type with these constraints which will be known at compile time `any` -> Any value conforming to these constraints which may vary at runtime
- tsss 8y agoI don't get the motivation behind this. I assume Swift has subtype polymorphism, so why not do this: func allEncompassingShape() -> Shape { return SpecialGiantShape() } This function returns some type that may be a subtype of Shape.
- jakobegger 8y agoBecause that does not work with generic protocols. You can't have a function return a sequence: func make_numbers() -> Sequence<Int> { // Cannot specialize non-generic type 'Sequence' } func make_numbers() -> Sequence { // Protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements } Whereas with this change you probably could at some point do something like this: func make_numbers() -> some Sequence<.Element == Int>
- tsss 8y agoWhat about func make_numbers() -> Sequence<Any> This should work as long as Sequence is covariant on Element. You could return any possible Sequence here, like Sequence<Int> or Sequence<Double>. The user of the function wouldn't know. You could also do something like func make_numbers() -> Sequence<Comparable&PartialOrder>
- vlozko 8y agoWhat about being able to make a ClosedCountableRange from that sequence? That can’t readily be done with an Any type without some type checking. Specifying an Int element type should automatically make it easier for you.
- justinrlle 8y agoI think your confusing Swift's protocols with something akin to Java's interfaces. I don't really know Swift, but it looks a lot like Rust, so I'm going to assume that they work the same. In Java, the following function definition compiles just fine: IShape getShape() { return new Rectangle(20, 40); } And, assuming that `IShape` has a `draw()` method, you can write: IShape shape = getShape(); shape.draw(); It works because there is dynamic dispatch occurring at runtime: the JVM will look for the implementation of `draw()` in the `Rectangle` class (not sure of the exact mechanism, but that's the idea), and call it. To find it, the value (here, shape) must holds a reference either to its class so the JVM can go and look for the implementation, or to a table of all methods it implements (I think it's the first). So the compiler code doesn't know the layout of the concrete type used, it just add instructions to go look for the implementation at runtime. But that's fine, because any Object in Java is in fact like that: a fat pointer, containing a pointer to the data, and a pointer to the implementations. I won't work in Swift because, as far as I know, there is no dynamic dispatch, at least by default. When you write the following: func render<T: Shape>(_ shape: T, at point: Point) { … } The compiler will know what is the concrete type of `T`, and so will use its implementation of the `draw()` method. It won't be found at runtime, it is known at compile time. What this means is that a protocol is not a type. This is the important part. An interface in Java is a type, because it doesn't dictate how the method is called, it allows the concrete type to live under the hood, and call the right method at runtime. A class in Swift is a type because you know how to call it, how to access it. But a protocol is just a set of constraints on a type, not a type by itself. That's why you need the `some` in return position. Well, you don't really need the syntax, but it helps understanding the difference with the "same" Java code. The `some` keyword says that the function will returns some type that will implements the `Shape` protocol. It will in fact return the concrete type, but this is not included in the type signature, so it can change, it can hide implementation details, without making a breaking change in the API. It also means that the following won't compile (I'm not sure here, but it works that way in Rust): func union(_ leftShape: some Shape, _ rightShape: some Shape) -> some Shape { if isEmptyShape(leftShape) { return rightShape } else if isEmptyShape(rightShape) { return leftShape } return Union(leftShape, rightShape) } Because here, all code path don't return the same concrete type. If you want different concrete types, you'll need the other keyword, `any`. `any` is in fact a lot like the interfaces in Java, because it uses dynamic dispatch under the hood (if it works like it does in Rust). The compiler will know how to turn the concrete type into the dynamically dispatched one.
- dep_b 8y agoWorking with Generics in Swift often made me feel I was missing something, pushing me to refactor my code once things started pushing past the trivial usage of generics because types started fighting back. Indeed I noticed that the requirement that types are declared “from the outside” made things harder. Another thing is combining protocols with generics. That feels a lot more convoluted than might be necessary. Seeing people express exactly what is the problem and what could be a solution is impressive. I hope we’ll see reverse generics soon.