Tumgik
mjahnke · 7 years
Text
Swift: Optionals
Intro
In the last post I hinted about a concept in Swift called “Optionals”.
In this post we’ll have a look at what an optional is, what so good about it and what the ? and ! means.
@]?&€!”/* Null pointer exception!
Disclaimer: The following section contains Java code, written by me, a Swift-developer who hasn’t seen decent Java code in almost 10 years. Pardon my French.
You might have heard of “null pointer exception” - it’s something that I hear the Java-developers at work mention from time to time at least. This is what happens when you try to operate on a null-object in Java.
Say for example that you’re passing a pointer to an instance of an object to a function, and that function will invoke a method on that instance:
public void accelerate(Car car) { car.hitTheGas(); }
If the calling code isn’t passing an instance of Car, but instead null (or a pointer to a Car instance that isn’t initialized) - the execution will come to an abrupt end because of.. well you guessed it - a null pointer exception.
In order to mitigate this, you can check for null before you go about with your business with said object.
if (c != null) { c.hitTheGas(); } else { // Awww shit we have to handle this case too... }
Objective-C (which used to be my poison) had another approach to handling this: shutting the hell up about it. The first days of ObjC hacking were great I tell you. “Wow - no null pointer exceptions!!”. But I promise you; it’s prone to produce not-so-easily-found bugs at times.
Wouldn’t it be nice if you could trust that the variable, c in this case, could never ever be null? Wouldn’t that be just fucking awesome? Yes it would…
Optional
An optional in Swift is basically the same thing as that variable c we just saw. It can either have a value or not.
You can think of an Optional as a box containing a value or nil. In order to use the value inside the box, you have to “unwrap” it. This can be done nicely (safe) or forcefully (dangerous).
Well “how will that help me then?” you ask…
var bodyArmor: Armor? // bodyArmor is an optional - it can be nil
First off - you have to be explicit when dealing with variables that can be nil. The above example tells the reader that “Aha - the player (or whatever object this might reside in) can either have a body armor equipped or not!“. That’s valuable information right there!
When reading the variable, you have to be explicit about the fact that it’s an optional too: let bodyArmorDefense = bodyArmor?.defense.
var health: Int // Health can't be nil - it can be 0, but never nil.
The above code states that the variable health is an Int and can’t be nil. It’s not optional. So whenever we’re dealing with this variable we don’t have to check for nil, and we don’t have to care about our application crashing because of our code trying to poke on an object that doesn’t exist.
What’s so awesome about the health variable now is that you can’t assign it the value nil. Ever.
health = nil // <- This won't compile!
So you’re supported by the compiler here not to make mistakes.
health = bodyArmor?.healthBoost // <- Won't compile either
Unwrapping
“Force unwraps”
You’re feeling lucky - Maybe you’re past Ballmer peak and you simply don’t give a shit so you don’t want to be bothered with nil-checks. .
health = bodyArmor!.healthBoost // <- Will compile, but also crash during runtime if bodyArmor is nil.
This is called a forced unwrap of an optional. And basically you should always try to avoid it if possible since this will crash your app if bodyArmor in this example is nil.
“Safe unwraps”
Say we have an optional holding a potential JSON-object.
let json: Json?
And we’d like to execute a function on that object:
json?.doSomething()
If json is nil - nothing will happen (like Objective-C nil-handling)
If json isn’t nil, the method doSomething is invoked
Even though this will “fail silently” it’s still better than Objective-C because we’re explicit about the fact that json can be nil here - we know it’s a valid scenario.
Another great way of safely unwrap options are if let and guard let - more about those another time!
Summary
Be explicit in your code.
Try to not use optionals.
Errors during compile time is better than errors in runtime.
If that fails; try to unwrap safely “?”.
If that fails; try again.. find a way to not do it forcefully.
If that fails; well ok use the god damn “!” but feel ashamed.
Bonus: A peek under the hood
This is an optional! Look how elegant it is!
// I've stripped this implementation down to get to the gist of it. public enum Optional<Wrapped> { case none case some(Wrapped) }
It’s an enum type, that’s either none or some. If it’s some - it also contains an “associated value” (another concept that we’re not going to go deep in to right now, but see it as a value that’s attached to the enum).
1 note · View note
mjahnke · 7 years
Text
Swift: Variables & Constants
Intro
This is the first entry in (hopefully) a series of short Swift tutorials where I try to cut the crap, skip the basics of programming and instead focus on the language Swift and what I think makes it great.
Where to write code
To get something up and running as soon as possible (since we’re here to write code, not setup a development environment), here are my suggestions:
MacOS and Xcode
If you’re on a Mac, download Xcode (it’s available for free on the App Store) and create a new “Playground”.
Online IDE
There’s a nifty online IDE for writing Swift by IBM called “IBM Swift Sandbox” that you can find here: IBM Swift Sandbox
Variables and Constants
Declare a variable
You can declare a new variable like this:
var what = “World” print("Hello \(what)!") // Prints "Hello World!"
You’ve just created a variable of the type String and given it the value “World”.
Type inference
As you might have noticed, you didn’t have to explicitly say that “I want this variable to hold a String”. That’s because Swift is smart enough to infer the type when you give it a value upon declaration.
If you want to be explicit, or perhaps you’re not giving the variable a value from the get-go, you can specify the type like this:
var temperature: Double = 30
If we wouldn’t have specified Double here - the compiler would infer that temperature is an Int
Declare Constants
By using the keyword let instead of var when created a new variable, you’ll create a constant. Constants can’t be changed after they’ve been initialized.
let mountEverestHeightInMeters = 8848
I suggest you always try to use let if you don’t intend for the variable to be changed.
Arrays
let fruits = ["Apple", "Pear", "Banana", "Lemon"]
The compiler infers that this is an array of String
You can access elements in the array by:
let firstFruit = fruits[0]
If you want to be able to modify the elements held by the array, you declare the array with var instead:
var food = [“Hamburger”] food.append("Pizza")
Create empty arrays
You don’t always have something intelligent to populate an array with when you create it.
var sports = [String]() or var digits: [Int] = []
The statements above will create empty arrays of a specific type.
Dictionaries
let realName = ["Batman" : "Bruce Wayne", "Spiderman" : "Peter Parker"] print("Batmans real name is \(realName["Batman"]!)")
You might notice the exclamation mark in the code: realName["Batman"]!. This is a forced unwrap on an optional value.
“What. The. Flying. Fuck?” you might ask. This is something I’m going to clarify in the next post. For now; just go with it.
Summary
var nickname = "@engineerish" <- Creates a string variable that can be changed
let height = 34 <- Creates an integer variable that can’t be changed
let options = [3, 6, 1, 9] <- Array of type [Int]
let mountainHeights = ["Mount Everest" : 8848, "K2" : 8611] <- Dictionary of the type [String : Int]
Arrays and dictionaries can store both primitive data types and reference types. Just jam stuff in there!
1 note · View note
mjahnke · 8 years
Text
Arduino Tutorial - 2 Player Pong on TV
Over the holidays I’ve been tinkering with the “TVout”-library for Arduino. Seeing your Arduino code outputting huge low resolution graphics on your TV is quite spectacular.
I hacked together a Pong game in order to try the library out, here’s how I did it.
Components
Arduino UNO
RCA connector (or a cable that you don’t mind ripping apart)
1x 1000 ohm resistor
1x 560 ohm resistor (internet says 470 ohm but that didn’t work for me)
2x Potentiometers
2x 100uF Capacitors (should be used together with the pots according to the Arduino starter kit project book.. hell I know)
The Circuit
Tumblr media
The RCA cable
I didn’t have an RCA cable laying around, so I made my own.
Tumblr media
Solder the two resistors to the (+) wire on the RCA cable
Tumblr media
Slide on the heat shrinks if you have any and solder jumper cables to the resistors.
Tumblr media
Finish it up with a final heat shrink.
Tumblr media Tumblr media
Test it out
Now you have everything in order to test the RCA cable with the Arduino. If you have an UNO - you should plug in the cable connected to the 1k ohm resistor to digital pin 9 and the other one on digital pin 7.
Add game controls
For this project I just added two potentiometers to a breadboard, allowing two player to play at the same time. See the schematics on how I wired them.
Tumblr media
Write the code for Pong
Pong is a very simple game and writing is a fun exercise to implement it. If you’d like to check out how I made it, you can find the full source code on my github.
Behold the result
Tumblr media
Suggestions for improvement
Feel free to grab by source code and modify it however you’d like. Some suggestions on what to implement:
An “AI” to make single player a little more exciting
A menu where you get to choose single player or multiplayer
Make the ball bounce at different angles depending on where on the paddle it hit
Read more
If you are interested in reading more about the TVout library you can check out the github repository for it.
I used this tutorial when tinkering with this, it had some great examples.
0 notes
mjahnke · 8 years
Text
Tutorial: Arduino Tetris
Making the Tetris game was a great weekend project. The circuit itself is pretty simple, the complicated part was obviously the code.
If you’d like to build one for yourself, here’s how I did it.
Material
2x MAX7219 (driving 2x 8x8 LED Matrices)
1x Arduino Trinket (or equivalent)
4x momentary buttons
4x resistors (I used 100k ohm)
1x 9v battery
Extra (perfboard, wires, soldering iron etc)
Build the circuit
Since I wanted my game to be handheld, I built the whole thing on a perfboard, powered by a 9v battery.
Tumblr media
Write code
The code I wrote is far from perfect, and some bugs still lurks around (spin a shape near the edge of the matrix and it will go outside for example). But it’s definitely playable. The code also supports hooking up a TM1637 digit display to show the score (number of lines cleared), but I ended up not connecting one to my game for now.
You can find the whole source code on my GitHub. Feel free to contribute with improvements.
Note that the pins in the code is not updated to work with the circuit above - you’ll have to re-assign the pins in the code to work with our circuit.
Result
A video posted by Mattias Jähnke (@engineerish) on Sep 17, 2016 at 6:41am PDT
If you have any questions regarding this project, throw a private message my way on Instagram!
3 notes · View notes
mjahnke · 8 years
Text
NSStackView + NSScrollView…
Over the years of hacking for iPhone, I’ve accumulated a certain self confidence in regards of Apples development environment and their frameworks. I know my way around Xcode if you will.
The other day I took this can-do-attitude and dove head first into MacOS development. This swimming pool wasn’t too deep apparently and I was stuck after one minute trying to make a NSStackView scrollable... This. Should. Not. Be. This. Hard. Where’s all these views coming from!? What’s a NSClipView?!
Anyway - I found some obscure e-mail thread on the deep web (aka not-the-first-google-result) that gave me a few hints - which eventually led to a perfectly scrollable NSStackView.
I thought I’d share this with you - the interwebz - if someone is having the same problems I had.
In the interest of not making this tutorial way too verbose: create a new project, open storyboard, add the components.. yeah - you know the drill.
Add the views and select the inner most NSView
Tumblr media
Add constraints to that NSView
Leading, top and trailing
Tumblr media
Select the NSStackView
Tumblr media
Add constraints to the NSStackView
Leading, top, trailing and bottom
Tumblr media
Admire your creation
The stack should now scroll just fine! But as you might see, it’s building from the bottom and up. This wasn’t the behaviour I was going for..
In order to fix that, we’re going to have to create a subclass of NSClipView and override the property “isFlipped” and return true. Then change the class of the NSClipView in interface builder.
Tumblr media
If you’d like to try this our for yourself, I uploaded my sample project on GitHub: https://github.com/mattiasjahnke/NSStackView-Scroll
1 note · View note
mjahnke · 8 years
Text
Tutorial: Party glasses
A while back I modified a pair of sun glasses. The vision was to become the center of attention at any party - I think the result was more like social suicide - but for the sake of this tutorial, let’s call them party glasses.
You’ll need
Adafruit Pro Trinket - 5V 16MHz
2x Neopixel (I used the ones with 16 pixels)
9V battery
Wires
Things to make it stick (I prefer hot glue and electrical tape)
A pair of sun glasses (I strongly suggest you don’t use your ray-bans)
Create the circuit
Tumblr media
The breadboard will bring down the swag level significantly, I suggest you wire it all up without it.
Modify the glasses
As I mentioned, I like super glue and electrical tape. It won’t win no beauty awards but this is a hack - and you’re late for that party where you’re going to ruin everyones evening by giving them epileptic seizures.
Tumblr media
The code
The neopixels are really easy to program, but if you’d like to try building a pair yourself and don’t want to write code - feel free to grab the source code for the animation below on GitHub
Watch your friends leave you
A video posted by Mattias Jähnke (@engineerish) on Aug 11, 2016 at 11:48am PDT
Note: This is also a great way of keeping your eye balls warm during the colder months of the year
0 notes
mjahnke · 8 years
Text
Bye Arduino IDE - Hello Atom
If you haven’t had the honor to try out the Arduino IDE... Well I’m happy for you. This is what the little devil looks like:
Tumblr media
It’s great for anyone starting just off creating Arduino stuff, but after a while you feel like you deserve better.
Atom.io (https://atom.io/) is a damn good text editor from the people over at GitHub. It’s great out-of-the-box, and there are numerous plugins if you’re in to that sort of stuff.
It turns out that there is a great package available for Atom for compiling and uploading Arduino stuff! http://platformio.org/ - they have both a standalone install for their IDE (which is built on top of Atom, if I read their site correctly) and as a package for Atom (https://atom.io/packages/platformio-ide).
Tumblr media
Above is a snippet from the Tetris project source code. As soon as I’ve given that abomination of a code base a serious make over - I’ll write the “part 2″ (which I’m sure you’re all waiting for, right?) of the Tetris project, make the source code available on GitHub and draw circuit schematics.
If you are going to code in public - at least use an IDE that gives people the impression of that you know what you are doing.
0 notes
mjahnke · 8 years
Text
Arduino Tetris (part 1)
While scavenging the internet for a new project, I came across Tetris clones running on Arduinos. I love that game so this was just perfect. This has obviously been done tons of times before, ranging from tiiiiny screen to whole freaking coffee tables.
Since I kinda like my current coffee table, I decided to go down the slightly more sane route.
I found a couple of LED Matrices (8x8 big) driven by a pair of MAX7219. These where perfect for my interpretation of this classic game.
Programming LED matrices was a skill I had yet to acquire, so I spent a night trying to communicate with them. After some serious misunderstandings and awkward moments between the three of us, I was on to something and we started to speak the same lingo.
Tetris begins - The origin story
Back in the day I made a Tetris clone in the language C#, this time around I didn't have the luxury of using cool objects, arrays and the stuff I'm used to (btw the reason why I do Arduino stuff at all - it's good to be reminded of the struggles of our forefathers…).
I started off creating ridiculously complex byte-matrices, representing the shapes of the game. But then I saw the light (or rather I found an open source project - http://wintris.codeplex.com/ - but I promised myself after that that there will be no more cheating)...
byte shapeZ = 0x4C80;
Let me explain! 4C80 in binary is 0100110010000000. WHOOOOOA - RIGHT!? No? Well, split that into groups of 4 and the magic is revealed;
0100
1100
1000
0000
Do you see how those 1′s makes up one of the shapes that we all know and love?
With some swearing and serious doubts if I’ve even ever went to the university - I managed to get that correctly displayed and animated on the “screen”.
Behold the results!
A video posted by Mattias Jähnke (@engineerish) on Aug 13, 2016 at 9:58am PDT
Next post will be about my farewell to the Arduino IDE (no IDE, you didn’t even serve me well), and some real game logic - scrolling Tetris shapes aren’t bad but we want a playable game, right?!
4 notes · View notes
mjahnke · 8 years
Photo
Tumblr media
Sneak peek of this weekends project ;) #electronics #arduino #diy
0 notes
mjahnke · 8 years
Text
Arduino Guitar
I made a guitar using Lego Mindstorms a few year back. It had it’s limits, yes, amongst them the fact that it gave you no rock star swag. Whatsoever.
Anyway, I decided to give it another try. This time using an Arduino and some real metal rods in the pursuit of the previously mentioned “rock star swag”.
The concept is pretty straight forward. A button, a distance sensor and a piezo for sound.
Tumblr media Tumblr media
I got to work, gluing two metal rods together. Minutes after this picture was taken I learned that super glue can be kind of sticky.. Even if you use news papers and all.
Tumblr media
I took refuge in the basement and continued on to add the “base” where the Arduino and battery would reside. I’m pretty happy with how the old plastic chalk jar turned out.
Added duct tape for that rough/classy look I was going for. And then I added some more.
Tumblr media
I prototyped the circuit on a breadboard.
Tumblr media
And... voila! Looks like a frickin’ bomb - and it’s sounds like tha bomb. No, it actually sounds horrible but I decided that sweet music was “out of scope” for the project.
Tumblr media
In the sketch I had a “sliding thingy” that would have added some complexity to the build, and I couldn’t really find any materials to build it from. Using your left hand is fine - makes you look like a rocking magician.
This project only took a few hours to build, so I can really recommend it to anyone looking for a weekend project (you can probably bump those “few hours” up to a full day if you’re going for something with a little more finish than I did).
Source code for what’s running on the Arduino is available on GitHub for anyone who’s interested!
1 note · View note
mjahnke · 8 years
Text
Weekend project: WriteOnly.io
So I was in this public forum the other day (a GitHub issue). During a discussion with someone, I needed some semi-sensitive information from the person behind the other screen (an e-mail address in this case).
This conversation was public... So you know - I didn’t want to post my e-mail address, and I guess the guy on the other end didn’t either (and who am I to ask for it?). Stalemate - right?
Imagine a simple service that could help us solve this dilemma. A “write only” document if you will (well - some form of read operation had to occur at some point but.. “writeonly.io” was catchy so bare with me).
So I had a solution...
The basic idea was that a user can generate two links. One link is for writing messages (the link I would have sent to the other guy if I had come up with this idea a week earlier), and the other link will list and read those messages (this one is for me).
To add on to the simplicity factor - keep it anonymous (who wants to deal with user accounts anyway) and let’s automatically delete documents after 24 hours (who wants to deal with a lot of data (yes - I’m an optimist) anyway?).
Let’s get crackin’
I haven’t written a website in forever, but as I recall, node.js is pretty damn neat. So I dusted off some old projects, looking for boiler plate code. Turns out everything I’ve ever written in node.js was deprecated so I had to do the whole tutorial-frenzy anyway.
Express, mongodb, some libs for unix time and uuid-generation, a sandbox heroku stack and I was good to go.
I had the functionality going in a couple of hours with about 100 lines of code, leaving only the tremendously boring act of implementing CSS. Apparently people like when websites look good or whatever. Googling “free css template” took care of that god forsaken task.
I really wanted that green little pad lock in the browser’s navigation bar... I took a “quick” dive into SSL certificates (about here was when the “let’s keep this project cheap”-approach ended).
Tumblr media
Check out the result here
1 note · View note