Hacker News new | comments | show | ask | jobs | submit login
Flappy Bird in Swift (github.com)
309 points by pjvds on June 3, 2014 | hide | past | web | favorite | 124 comments

As a C# developer, I can read and understand the code without any issues. That's a good thing for Apple. I'm sure Objective-C is great but it's too foreign for me and didn't want to toy with it for fun, not worth the effort. But I can write an app or two with this one.

I get where you're coming from - but in my experience, the barrier is totally psychological. Objective C isn't that unusual a language - the syntax is a bit foreign, but nothing that takes more than a couple of days to wrap your head around.

You'll spend far more time getting to grips with Cocoa/Cocoa Touch.

the barrier is totally psychological

Of course it is. It's certainly not a physical barrier. But psychological or not, other languages don't have a similar barrier.

> other languages don't have a similar barrier

Lisps have the RPN psychological barrier. Python has the significant whitespace psychological barrier. etc. Any language can present someone with some psychological barrier.

I think the OP's strongest point was, Objective-C the language is pretty trivial to learn quickly (after all, it's just C with message passing). You'll spend far longer trying to learn the Cocoa APIs than you will spend learning Objective-C-the-language.

For instance, I decided to try to learn swift and SpriteKit at the same time. I spent far longer looking up methods on SKSpriteNode than I did looking up language constructs. (i.e. I assumed "let" was the same as in ES6 and couldn't figure out why the compiler was mad.)

Okay, I meant more that there's not a skills barrier in terms of actually learning to use the language. The syntax can be intimidating, but once you've spent a couple of hours with it, it's not an issue any more.

It's far more difficult to get to grips with how the APIs work.

That's my problem. I can't even find the entry point for this application. Looking at AppDelegate.swift I see an unused var (window) and that's it.

@UIApplicationMain is the key there, from what I can see. An Objective C iOS app typically includes a main.m entry point which calls UIApplicationMain and passes the AppDelegate. This seems to have been removed in favour of what Swift is calling a "declaration attribute", which presumably does the same thing.

In this sense, the code is even less clear than the Objective C implementation.

They removed the need for main by making global scope the entry point.

I just started exploring the Book: The Swift Programming Language by Apple Inc.

Link: https://itunes.apple.com/us/book/the-swift-programming-langu...

Hope it helps.

Note that near the top of "A Swift Tour" there is a link to the playground which you can download and open in Xcode 6.

Wow, that is cool. Learning Swift is going to be fun.

Direct link to the playground file: https://developer.apple.com/library/prerelease/ios/documenta...

Can anybody put this book somewhere outside itunes? Thanks!

I guess Flappy Bird is now a tier 2 "hello world" :)

It's the new Tetris. Years ago Tetris was the typical non-trivial target you were shooting at when trying out stuff.

I think 2048 is that.

I was disappointed that they didn't use it as "The simplest possible game" in the WWDC presentation

It really isn't any more complicated than their typical SpriteKit demos.


Is it really copyrighted though?

yes. IANAL but... copyright law in the US is such that, in essence, everything is copyrighted (to some degree) the moment it is created unless you explicitly state otherwise.

When dealing with anything legally distributed / created in the US there are many questions, but "is it copywritten" should be one of the last ones, because the answer is always YES.

"Flappy Swift" then.

It certainly would be cool if it were.

Flappy Bird in Cobol!

In the meantime, check this port https://www.youtube.com/watch?v=jE1uKIE4e5U out.

Author here - I didn't expect to see this here this morning. I'd intended to write a longer post :)

In any case, here's a few things I learned about swift yesterday building this. Please note that I have about 4 hours swift experience, so feel free to correct anything I say that's wrong.

1. To make properties on a class you simply declare the variable on the class e.g.:

    class GameScene: SKScene { 
      var bird = SKSpriteNode()
      // ...
2. The APIs generally have shorter names and it's really nice. E.g.

    SKTexture* birdTexture1 = [SKTexture textureWithImageNamed:@"Bird1"];


    var birdTexture1 = SKTexture(imageNamed: "Bird1")

If I understand it correctly, any overloading `inits` basically look like calling the constructor on the class, whereas any class functions will be called like this:

    var flap = SKAction.repeatActionForever(animation)

3. You can put inline blocks and it's great

    var spawn = SKAction.runBlock({() in self.spawnPipes()})

4. The typing is really strong - this takes some getting used to. For instance, `arc4random()` returns a 32 bit unsigned integer. This means before you can use any operators on it you have to make sure you're using compatible types. e.g.

    var quarter = UInt32( self.frame.size.height / 4 )
    var y = arc4random() % quarter + quarter;
If we didn't use `UInt32` to convert `quarter` we'd get an error. After you get the hang of this, it's actually really nice.

5. I use `var` everywhere and I'm pretty sure I should be using `let` a lot more. I haven't worked with Swift enough to have a strong intuition about when to use either.

I should also mention that my code is just converted from Matthias Gall's code [1].

I also want to put in a shameless plug that the point of making this was to advertise the "Making Games with Swift" class that auser and I are building. If you're interested, put in your email here: https://fullstackedu.com

I intend to redo this more fully with Playgrounds. I've been looking for a way to teach kids programming for a while now (if you recall, auser and I built Choc [2] a few months back). I think Playgrounds in Swift are finally the tool we've been waiting for.

[1] http://digitalbreed.com/2014/how-to-build-a-game-like-flappy...

[2] http://www.fullstack.io/choc/

EDIT: added choc

I don't have XCode to try it out, but according to the book, you can replace

  var spawn = SKAction.runBlock({() in self.spawnPipes()})

  var spawn = SKAction.runBlock({self.spawnPipes()})
or even

  var spawn = SKAction.runBlock() {self.spawnPipes()}

  var spawn = SKAction.runBlock {self.spawnPipes()}
EDIT: formatting for code

What about this?

  var spawn = SKAction.runBlock self.spawnPipes

Heh. Reminds me of when I correct people for

  if var == true {...}
or (and I have actually seen this)

  if (<expression> == true) {
      return true;
  } else {
      return false;
I sometimes think that simply giving those 5 lines to a person and observing if they make a face like you've handed them a bucket full of day-old fish is a better test for programming aptitude than anything.

  if var == true {...}
In some languages var might be truthy but not equal to true. The falsy values may be more of a problem at times.

However in the strongly typed swift I don't think it will be a problem as I suspect (but haven't read/tested enough yet to confirm) that only false and nil will be falsy and that comparison with true will throw errors if var isn't of bool type.

Just tried it. In Swift:

  3 == true    // Give an error (operator overload doesn't cover this)
  true == 3    // Returns false
  nil == false // Returns false
You can't use nil or integers directly in an if statement without a function to return a logic value.

Yes, such languages exist, and even in C++ if (x == true) is different from if (x), given that x is any number kind other than boolean, but my comment was only for the case when the two would be equivalent.

I'd argue the second is clearer in many cases. Readability trumps conciseness any day.

I agree that readability trumps shortness of code. I want not for APL nor code run through a javascript minifier.

But the branch and explicit boolean comparison are additional structural complexity (not just "verbosity") and invariably harms readability to me. Care give a poster child example for where it helps readability? Unless it's unclear <expression> results in a boolean - a problem better solved through better naming - code like this forces me to perform the equivalent simplification in my head to understand and reason about the code, a process fraught with error and distraction from my actual task.

Really? In which cases would the previous example be clearer than

    return expression;
What readability does the verbosity add?

Are you sure this should work? I checked the grammar once more and it seems that closure-expression should always be enclosed in { ... }

This is awesome and I didn't know this. Thanks for posting it - I don't have much swift experience so I assume there are several things in the code that will be shown to be non-standard.

> I don't have much swift experience…

Considering the language has only been public for <36 hours, I would imagine effectively no one outside of Apple (and its Alpha partners) does.

Which will not stop recruiters from seeking candidates with 5 years experience in Swift.

I think just the fact that you were able to build a game with just 4 hours of learning a new language speaks volumes about Swift's barrier to entry. Well done!

I think it speaks more to the author's prowess, not to the fantastic magic powers of Apple's latest walled garden.

Any up-to-date C# developer already knows Swift.

Any up-to-date Java developer already knows Swift :)

Any up-to-date Swift developer already knows Swift :-p

But the code was just a port/convert, seems relatively non-trivial to do that in 4 hours.

I supposed "relatively" is the key word here. To me, that'd be a great feat. To others, not that special.

"I use `var` everywhere and I'm pretty sure I should be using `let` a lot more. I haven't worked with Swift enough to have a strong intuition about when to use either."

I think you should type let everywhere, except when you cannot get away with it.

So, it is var when declaring a loop variable. Elsewhere you almost always can introduce a new name. So, instead of

   X += 1

   let newX = x + 1
Those rules are too strict, but not much so, and you will learn the difference faster if you overcompensate.

If you find yourself creating a newerX, a newestX, etc. you may be better of with a var, but chances also are that you are better of writing your code differently (for example can you iterate over a constant array of values instead of doing x+=1 a few times? If your function needs to create 10+ Local variables, can you factor out a function?)

A couple more interesting swift features that seemed a bit weird to me after skipping through the reference:

1. Strings, arrays and dictionaries are value types (like structs in C# - stored on stack, not on the heap) with special copying rules for arrays.

2. Custom operators - can be defined as a sequence of "/ = - + * % < > ! & | ^ . ~" characters and made prefix, infix or postfix. There is an example in the reference that defines a prefix operator "+++" for vectors

Good work. I'll have to do 2048 instead, I guess :)

I'm quite impressed so far. Having been an Objective C and Ruby engineer, so far Swift seems to offer the best of both.

That said, OpenGL support doesn't appear to be finished yet.

If you're new to functional programming styles this swift project might be more relevant: https://github.com/maxpow4h/swiftz

I got mixed feelings about the language at first sight. I guess my mammalian brain recognizes languages based on the particular combination of the following naming decisions.

* func, function, fun, defun fu, funct

* CamelCase vs snake_case

* whitespace, semicolon or comma usage

* var, int/integer/uint64/Integer/

* choice of (), {}, [] or better (){a[]}

* import/include/require, class/class, override, self vs this, new vs Class()

PS: next time you design a new language just make a random unique combination of the above.

> PS: next time you design a new language just make a random unique combination of the above.

That's my impression whenever I see a new programming language too. Why would someone switch to your language if the syntax is just the same boring old syntax they've been using in another language?

Why would someone switch language if the familiar concepts have been given different names for no good reason?

Use different syntax and naming for the things that are genuinely different about your language.

Because in this case, it's an alternative to a language (Objective C) with a not so boring esoteric syntax.

Not boring at all - but I'm not sure this helps adoption any. :)

Since I'm being downvoted... please excuse my poor attempt at sarcasm.

What I'm saying is that I sometimes get the impression that language designers randomly change up syntax just to make their language look different, and thus superficially more appealing to users. Just like any other kind of product.

It would be pretty weird to base language switching decision on syntax similarity.

Do you see the amount of people that complain about Pythons white space? Plenty of people avoid it for that reason alone.

>>mammalian brain

Woof woof! I got one too. My view of Swift is: not a good enough reason not to continue using Lua for the same problem.

Always had a problem with Objective C, could never read it (Android Dev) but this right here is pretty impressive. I like the mixture of language features. But my only question, are you still locked to using an mac to develop for iOS. I guess since the language is closed source it depends on some osx libs at compile time.

Yes, you still need a Mac to develop for iOS. Come to the dark side! :)

Android developer here with a Macbook Pro. I'm honestly thinking about taking the leap and getting an iPhone, depending on how the 6 looks like. But Swift enticed me very much.

You won't regret it

We have cookies.

What is so hard about reading Objective-C? I've seen this as a very common thread with people celebrating the arrival of Swift.

I'm not trying to be flippant and I understand that the named parameter format may throw some people for a loop, but I'm curious why it appears to be such a limiting factor in trying Objective-C.

From the GIF in the readme, it looks like collision detection is broken.

I'm terrible at flappy bird - I can /sometimes/ get through the first pipe. Rarely.

I didn't build the collision detection yet just b/c I actually think it's more fun to play this way.

That said, we'll add it before too long.

This being the only code sample of swift I've seen, my overriding takeaway is that for the basic stuff it's remarkably similar to Objective-C with a lick of paint.

If people really take to swift, it'll be interesting to see if that's because it creates a shift in programming style, or because people really are just afraid of small syntactical differences.

After skimming through the code and knowing that it was a job that took only four hours, it's very likely that this is just objective-c code written in swift(as the saying goes, you can write java in any language). It will take a bit more time to learn the idiomatic swift style and implementation.

Part of the reason it looks like that is because I don't really know swift all that well. One of the great things we have in Swift is more functional features like closures, named functions, etc. I expect we'll see a lot of higher-order functions being used and that would clean it up a lot.

Readability matters - maybe the Objective-C verbiage melts away once you're up to speed, but it certainly puts you off wanting to get there.

I find obj-c super readable, other people don't? I mean, take two hours to get used to the bracket syntax for message sending and it's super readable although a bit verbose?

Same here.

All you have to do is get over named parameters, square bracket message passing, and overall verbosity, and you know enough to read/understand Objective-C code.

If you can get past those three differences, Objective-C is remarkably similar to Java and other OOP languages.

Personally, I love the verbosity. The code pretty much just explains itself.

Swift is a welcomed change though. I'm very optimistic and excited about the future of iOS going forward.

Please take this in good humour but I couldn't resist:

> All you have to do is get over named parameters, square bracket message passing, and overall verbosity

Translation: "All you have to do is get over it's poor readability and it's quite readable!"

> Objective-C is remarkably similar to Java and other OOP languages.

Translation: "Objective-C is as readable as several other unreadable languages".


Readability isn't about familiarity as much as it's about clarity and a lack of boilerplate. Verbosity is in most cases the antithesis if readability. I think there can be exceptions (maybe some verbose DSLs that manage to map cleanly from your brain to the code on the page) but if the verbosity comes from boilerplate or visual clutter then verbosity is a strong point against.

That's always been the intuition. If swift maintains a distinct Objective-C style but with more approachable syntax, then that suggests the intuition is true.

Swift is definitely more approachable than Objective-C for new developers.

I would imagine that is very on the reasons for creating it.

For new developers, or for developers coming from other languages?

I think a lot of the trouble people have with starting to develop apps for Apple platforms actually comes from trying to figure out the APIs and style, while at the same time battling against unfamiliar syntax. From the little I've seen, Swift doesn't change the first part of that very much.

I think both. I have a young cousin who is starting to show interest in programming, and when I think of showing her Objective-C, I grimace inside because it has taken me so long to become comfortable with it, and I'm coming from other languages and years of experience. But I think I can walk through Swift with her, and we can learn it at the same time - me bridging the gaps because I come from another language, and her learning how to program for the first time.

Both. The APIs and style sure are issues.

But there are plenty of language constructs which exist only in Objective-C.

I am really intrigued by the obj-c interop capability of swift, namely interactions between blocks and closures / anonymous functions.

I can see my AFNetworking code becoming much, much more readable now, without the need to @weakify/@strongify self on both sides of the block, but just add a blanket '[unowned self] in' inside the closure.

Swift is a new programming language. Does this implementation also use Metal? What is the Scene Kit relation to Metal?

SpriteKit and SceneKit is targeting casual games. Metal is an API that is close to GPU and is meant to replace OpenGL for console level games.

This only uses SpriteKit, for 2d graphics. SceneKit is for 3d stuff.

This may be a stupid question but is the language in some way tailored to game programming? Apple's examples at WWDC were game companies, their coding demo was a game, and this is the first project I've seen written in it - and it's a game.

Games make easy examples because you can do a simple render loop and input. Most people understand the concept of sprites and basic animation.

Apple's UI frameworks are all MVC based, which means multiple classes and apple specific UI terminology.

Additionally, they're a quick route between code and something visual. If the demo yesterday had been "look how easy I can make a tableview", no one would have cared much, but the circus scene had motion, lights, and barely any code. People love spectacle.

That reads a lot more sarcastic than it should have, but it's unfortunately true. Swift was announced in front of a room of people who needed to be convinced to start migrating from something they all know (ObjC) in favor of something new, so you have to win them over quick.

I think you're missing this is building off of other things that are meant for games like scene kit etc....

The language isn't tailored to it, but there are things it makes easy that are. If that makes any sense.

There's also a new graphics API, 'Metal', though I don't know if that has anything to do with it.

Flappy Bird in Racket | https://github.com/soegaard/flappy-bird

Man, apparently dr racket format looks like a hot mess.

A normal Racket file is a straight forward text file.

In Flappy Bird I used inline images, as in (define bird <the-bird-image-here> ) This makes it simple to distribute the source and images as a single file, but unfortunately the resulting file is not pretty.

In short: to see the source open it in DrRacket.

pretty neat! I am not an iOS developer but if i understand correctly this uses the new Sprite Kit stuff included in iOS8 for 2d rendering right ? Is this a threat to existing 2d/game engines ? Not sure where SpriteKit integrates into the existing stack for making a game.

Looks like a good way for Apple to lock the developers to their platform. In past glory days people used to make games for iOS first and consider porting to Android much later. These days developers think cross-platform from the start, esp. since it's much easier to test waters and iterate on Android. I guess that SpriteKit is an attempt to stop this trend. Smart move by Apple IMHO, but perhaps a little bit too late.

I see your polite, critical, level-headed opinion has been down voted into gray dust, despite my meager support. I entreat those who pass by here to drink in my own following opinion: I think you're operating from the democratic ideal that "all people will opine equally about all topics at all times."

The departure from this ideal, I've discovered, is that there is a "Practical Crowd" who will swoop through when questions of practicality, such as cross-platform compatibility come up. Their opinions will be nearly absolute and they will be all but intolerant of the "weak" who claim that merely targeting Windows, Linux and OSX is "enough." They will justify with numerous cherry-picked examples from history, starkly, if not carefully, considered arguments toward the future, and with evidence of grit on their fingers from the present, in which the particular ideal is espoused. At that time, they will down vote anyone deviant enough to cheer for Swift.

Yet, currently my friend, the Apple Crowd has the floor. Any practical concerns are scheduled after the celebration. Think of this when you read the next cross-platform thread and see the Apple fans trying to get a point in edgewise amongst The Practical. There is very little global reality, mainly local basins of morality.

SpriteKit was released last year with iOS 7. It's a pretty much self-contained 2D game engine like Cocos2D, including stuff like physics simulation. iOS 8 is going to ship with SceneKit, which is similar but for simple 3D games.

How extensive is the physics engine implementation?

Wikipedia claims that SpriteKit uses the Box2D engine internally: http://en.wikipedia.org/wiki/Box2D

In iOS7 it is Box2d, but not all of it was implemented. There is likely a lot more now in iOS8. There is also a 3d version which I assume uses Box3d.

Well that didn't take long...

If Swift has namespaces why are classes still prefixed? "SKScene" for example.

Objective-C interop.

Does this need IOS8 to run?

Is there a way to get that without being a signed up dev with Apple?

Apple has stated that Swift apps can target iOS 7/8 and Mavericks/Yosemite. You do need access to the dev program in order to get access to the Xcode 6 beta.

It shouldn't need iOS 8 to run because it compiles down to the same native code that Objective-C apps and Rubymotion apps do.

> Is there a way to get that without being a signed up dev with Apple?

You need to be in the iOS developer program to get iOS 8 beta.

Someone needs to add Swift to the linguist gem

OK, that was fast!

2k+ Github stars in less than 24h? OMG

Swift looks fine, the only thing I don't like its that is for Apple only products... that kinda defeats the purpose of having a programming language.

> Swift looks fine, the only thing I don't like its that is for Apple only products... that kinda defeats the purpose of having a programming language.

Tell that to Microsoft ;)

Apple is the new Microsoft.

There are many programming languages that in practice tend to be locked to one platform or another. C# isn't only on Windows and Objective-C isn't only on iOS, but very few people learn either of those languages with the expectation of "write once, run anywhere." (I've found that generally people who use C# on other platforms do so because they already know C# and don't want to learn something else.)

On principle I'd like to see Apple put Swift under a free software license of some kind and ideally make a cross-platform reference implementation, but realistically, even if they do that it's unlikely to ever get wide use anywhere but Apple products.

You can write code for non-apple products, its just that the libraries are lacking. I don't see how this defeats "the purpose of a programming language".

apple fanboys keep downvoting!

Good luck compiling Objective-C on Windows :)

Ye-es, except:

  "Apple has recently added new functionality to their runtime, including built-in exception handling, etc. Hopefully these will be ported to the GNU runtime in the future."
My general point is that programming languages don't have to be cross platform to be useful. Certainly handy from a developer's point of view, but just a convenience.

Pretty sure you can compile Objective-C on Windows, since gcc supports it, and OpenStep worked on Windows.

It's Apple's libraries you don't get on Windows.

FAST AS HELL! :P Thanks a lot!


I was curious when I saw a tests folders, but it was just auto-generated files with no actual tests. =(

Swift hasn't even been out for 24 hours yet, give the guy a break! ;)

Share the latest about Swift here! Be part of the biggest page for the language. Looking for admins. https://www.facebook.com/swiftofficial

Applications are open for YC Summer 2018

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