Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Show HN: 2048 in Swift (github.com/austinzheng)
92 points by austinz on June 4, 2014 | hide | past | favorite | 34 comments


>> Still have no idea how to make things private, public, or protected. In Objective-C you could hide internal details away in the .m file. In Swift, everything is exposed by default.

I think it just hasn't been released yet. It's part of the Known Issues section of Xcode 6 release notes[0].

[0] http://adcdownload.apple.com//wwdc_2014/xcode_6_beta_ie8g3n/...


I asked a Swift engineer named Greg about this yesterday at a Swift lab at WWDC -- he said that it is forthcoming, but gave no estimates or timelines. Exception handling, however, doesn't seem to be on the roadmap.


Count me in the "happy to not have exceptions" camp.


I asked an engineer too, and he said exception handling was planned. So that's that :)


Can someone give a quick overview of whats going on with this code? I'm feeling a bit lost on how enums are being declared and used in swift.

  enum ActionToken {
    case NoAction(source: Int, value: Int)
    case Move(source: Int, value: Int)
    case SingleCombine(source: Int, value: Int)
    case DoubleCombine(source: Int, second: Int, value: Int)

    // Get the 'value', regardless of the specific type
    func getValue() -> Int {
      switch self {
      case let .NoAction(_, v): return v
      case let .Move(_, v): return v
      case let .SingleCombine(_, v): return v
      case let .DoubleCombine(_, _, v): return v
      }
    }
    // Get the 'source', regardless of the specific type
    func getSource() -> Int {
      switch self {
      case let .NoAction(s, _): return s
      case let .Move(s, _): return s
      case let .SingleCombine(s, _): return s
      case let .DoubleCombine(s, _, _): return s
      }
    }
  }


Swift's enums are like Rust's enums, so they're much more powerful than C's enums:

In C an enum can assume one of multiple predefined values of type `int`.

In Swift an enum can work like that too, but it can also assume values of types other than int. This is similar to the behavior of the unions in C, but more high level, with proper safety checks in place.

In Swift enums can also have methods, so there are two methods to return fields from the values contained in the enum —regardless of the actual type being held at that time.


The computer science name for that is sum type, the (or maybe just the simplest) implementation a tagged union (maybe I'm making up that distinction; Wikipedia thinks they are synonyms (http://en.wikipedia.org/wiki/Sum_type)). You can do ~the same~ in C with a struct and an union:

    typedef sruct s
    {
      int type;
      union
      {
        int i;
        float f;
        double d;
      } value;
    }
But there, it is up to you to make sure that you only read the int/float/double if the 'type' field indicates a int/float/double was stored. Higher-level languages enforce that you can only read the union as being of type T if you wrote it as type T.


  case let .DoubleCombine(s, _, _): return s
Is the underscore a special character in this case to tell the compiler not to read in the value of those arguments? Or is it actually loading in "second" and then "value" into an argument named _?


Assuming it's the same as other pattern matching langs it is a wildcard that signals the intent that you don't care about what value those would be.


And the functions there are examples of pattern matching in Swift.

To the GP. That code example is a very good example of just how different Swift code be from Objective-C.


It's the same as case classes and pattern matching in Scala [1]. Or case expression and pattern matching in Haskell [2]. Or in OCaml [3]. Or in Rust [4].

[1] http://docs.scala-lang.org/tutorials/tour/case-classes.html

[2] http://learnyouahaskell.com/syntax-in-functions#pattern-matc... "case expressions" at the end of the page.

[3] http://ocaml.org/learn/tutorials/data_types_and_matching.htm...

[4] http://static.rust-lang.org/doc/master/tutorial.html#control...


> case let .NoAction(_, v): return v

That's amazingly awkward syntax for a brand-new language. "case let"? In many other languages with pattern matching and destructuring, the "let" occurs implicitly.


The reason why they don't do that is that you can reference variable names:

    foo = 1
    switch bar {
      // Equals the value of (existing) variable foo
      case foo: return 0
      // Catch-all, binds `foo` to whatever is in `bar`
      case let foo: return foo + 1
    }
(My syntax might be off, I've never written Swift)

To do this in Haskell, you'd have to write something like:

    foo = 1
    case bar of
      foo' | foo' == foo -> 0
      foo -> foo + 1
Because you're only able to pattern-match against literal objects (constructors or numeric/string literals).

This might be different in some other ML-like languages, or there could be GHC extensions for this, of course.


In Swift this could also be written as

> case .NoAction(_, let v): return v

Putting it at the beginning makes it apply to all the variables in the parens (although in this case they are ignoring the first one by using the underscore).

Using "let" makes it immutable; you can also use "var" there to make it a variable you can modify in the case body.


Creator here. Glad people like it! I do have plans for slightly less useless projects in the future, but I did have a couple of reasons for building this particular project:

- I wanted to try out Swift and see how it felt in practice to build a reasonably-sized project in it - and to see if the Xcode Developer Preview was anywhere near up to the task. I also wanted to see how the Cocoa APIs were going to work with Swift.

- I had an existing Objective-C implementation that I could work from. I wanted to see if Swift could make the implementation easier to read, more elegant, etc. While the original is hardly a thing of beauty, I thought it still might be useful to see how business logic to perform the same task might differ between the two languages.

I hope people who take a look, fork the repo, download and play with the code will enjoy reading through it and maybe take it as a taste of how things might be done (or not done) in the future.


As an aside, it's interesting that GitHub as added support for Swift language detection so quickly, yet I frequently read stories (on HN too) about their passiveness to correct or add other (sometimes more) popular languages.


This likely has a lot to do with how they do detection.

Swift uses the .swift extension, which is pretty unique, so detection is as simple as checking for the file extension with a very low risk of a bad classification.

Some of the older, more popular languages uses more common file-suffixes, which may be shared between multiple programming languages, which has a negative impact on classification accuracy.


Yes. In support of this theory: Github does not syntax color Swift files yet (eg. https://github.com/austinzheng/swift-2048/blob/master/swift-...)


GitHub never bother. People send pull requests to their Linguist repo. If you want a language supported, do that; you only need to edit a yaml file and add some code samples.

I added Game Maker Language, for example.


There were article about how FlappyBird is the new HelloWorld these days. Most probably some-what humorous but it's great to see how many resources and projects have already been developed in Swift.

Shameless Plug: Want to learn Swift? Check out [http://www.LearnSwift.tips]


Normally I'd ignore the shameless plug but that's a nice set of tutorials you've put together there.


I was playing with it a bit this morning porting a helper XML parsing class[0] I have over to it and building a simple RSS Reader project.

I'm one of those people that really likes objective-c but I was surprised that when I had to go back to working in objective-c this afternoon I started to realise how much time Swift would save me. I feel like at a glance it's harder to understand the code but it requires way fewer keystrokes and overtime will probably become much easier to understand at a glance.

Overall I really like it. I'll have to write a lot more code in it first but I could see myself switching to this for all my iOS code when iOS 8 is released.

[0] https://github.com/KieranMcGrady/KMXMLParser


I guess this whole "X in Go" trend is now being replaced with "X in Swift"


I think the trend this joins is "2048 in Y", not "X in Go"...


It is not a trend, it is just people comparing a new tool to known tools.


Kudos for crediting "Threes"! That game doesn't get enough credit amidst the popularity of 2048.



Is it cool to post projects like this in GitHub? (give Apple's NDA/PLA for iOS Dev Center members).

I ask because I have some things I'd like to post but am reluctant.


They just changed it in the new developer agreement, that you probably agreed to if you logged into your developer portal.

It's under "Information Deemed Apple Confidential". "Further, Apple agrees that You will not be bound by the foregoing confidentiality terms with regard to technical information about pre-release Apple Software and services disclosed by Apple at WWDC (Apple's Worldwide Developers Conference), except that You may not post screen shots, write public reviews or redistribute any pre-release Apple Software or services."


> You may not post screen shots, write public reviews or redistribute

Well, count me out. I like to work free.


AFAIK NDA's can't cover anything that's publicly available. Apple announced Swift at a publicly streamed press event and they have made a Swift language guide available publicly on iBooks. My guess is they want people using it so that if people do start to switch to it when iOS 8 comes out there will be help available on the usual places (Stack Overflow, forums etc.) and people can find bugs.


Funny how 2048 is now the new "hello world!" :)


does anyone else fear there will be tons more duplicates on the app store of apps re-written in Swift? End users won't see a difference.


You're putting the whole thing inside GameModel? Are you serious?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: