Looks like the wait is over.
Some of the videos from ElixirConf 2016 are starting to get posted over at confreaks.tv.
I know what I’ll be doing with my evenings for the next few days.
Looks like the wait is over.
Some of the videos from ElixirConf 2016 are starting to get posted over at confreaks.tv.
I know what I’ll be doing with my evenings for the next few days.
That’s a bold question to ask. But I’ve been thinking about it.
As a member of the iOS developer community, I see people interested in learning how to create iOS apps almost every day.
I’m a member of various Facebook groups dedicated to share tips and tricks for iOS development, or just asking simple questions to the community. It hurts a little when I see someone new to this world asking, for instance, how to download an image from the network and set it to an UIImageView, and all the responses just tell them to “install this pod,” or “download this library.” You can translate that example to almost every common problem new developers face when first starting to learn iOS Development.
Why it hurts? Because these youngsters are never going to learn all the details behind doing what they can so easily accomplish with a pod install
.
I often respond with “it’s not that hard, and you don’t really need all of Alamofire to do that.” And that’s true. To download an image from the network and assign it to a image view you, at most, need 30 lines of code.
The open source community makes it so easy to add code that a) maybe you don’t need, b) maybe you don’t fully understand, that I fear the new generations won’t really know how the system works, but will know really well how CocoaPods or Carthage works. (Remember left-pad?)
If you’re someone starting in this trade, I urge you to spend some time learning what the ecosystem you’re trying to start developing for is really like, it being iOS, Rails, the week’s popular JavaScript framework, whatever.
Spend some time learning what it’s really like inside the frameworks you’re going to be using for the next years. Learn their tricks. Hack them.
Don’t get me wrong: using third party code can be (and is) a really easy solution to get things done. But in my experience, the actual learning happens when I get in there and mess things up. Don’t be afraid to mess things up.
The next time you’re trying to figure out how to do something specific, try to come up with a solution, and only then, look at what everyone else is doing. Rinse, repeat. That’s how you get good at something, not just blindly using someone else’s code.
Look for mentors that don’t show you the easy way, but that guide you through the rough way.
I’ve been writing Elixir for my main backend needs for the past few months and I’ve really liked it — specially its syntax. In fact, I’ve gotten so into its syntax that I’ve often found myself trying to write Swift as if it were Elixir.
Oops!
So I decided to experiment a little bit with bringing my favourite syntax from Elixir over to Swift natively.
Disclaimer: This is just an experiment. To get this to work on an actual project, a lot more work needs be done.
Elixir is a functional language that’s gained a lot of traction in the past few months thanks to its simplicity and core features, such as the supervision tree.
Every type in Elixir is a value, which means that it gets copied when passed to a function — the function gets a new copy of the value, which it can then modify without affecting the original instance.
> aMap = %{a: 1}
%{a: 1}
> bMap = Map.update(aMap, :a, 0, &(&1 * 3))
%{a: 3}
> aMap
%{a: 1}
> bMap
%{a: 3}
Also, Elixir has this great “pipe” operator that lets you write cleaner code and streamline data manipulation in a really easy way:
> cMap = aMap |> Map.update(:a, 0, &(&1 / 3))
The “pipe” (|>
) operator takes the value on its left and passes it to the function on the right as its first parameter. This is included as part of the language and works with any function.
Let’s bring that to Swift!
In this example, I’m going to use two simple struct
s (value types in Swift):
struct Company {
let name: String
}
struct Person {
let name: String
let work: Company
}
let apple = Company(name: "")
let joe = Person(name: "Joe", work: apple)
A characteristic of functional programming languages is that they strive for immutability. Vaues should not mutate during program execution, but copying values and modifying them is good.
Tipically, if we wanted to update joe
‘s name, we’d do something like
joe.name = "Joe Wood"
If we did this, the Swift compiler would raise two errors:
name
property on Person
is declared as a constant (let)
, which means it can’t mutate during execution — a change to var
is suggested.joe
instance was declared as a constant (let
), which means it can’t mutate during execution — a change to var
is suggested.What we don’t want, though, is enable the ground to shift under our feet, so let’s keep everything as a constant.
Another approach would be to create a function that did so:
extension Person {
mutating func update(name: String) {
self.name = newName
}
}
But again, that mutating
keyword there is a code-smell in the functional world. The way to do this the functional way is:
extension Person {
func update(name: String) -> Person {
return Person(name: newName, work: self.work)
}
}
We created a function that changes only one property on the instance — it receives the new value for the property, and returns a whole new instance of the type with that value replacing the original one.
joe.update(name: "Joe Wood").name // Joe Wood
joe.name // Joe
Now, the problem with this is that the function that we created is operating on the type-instance.
Note: In Elixir, a map literal can be written as
%{a: 1}
, but to transform and operate on that instance, we have to use theMap
module. That’s kind of what we want to achieve here.
We want that the Person
struct (or module, if you’re thinking in Elixir) to have a series of methods that receive Person
instances to operate with.
In order to achieve that, we need to do a bit of groundwork.
There is a concept in functional programming called “data lenses”. Explaining in detail what a data lens is, is way out of scope of this post, but you can read more about it here and here, and generally, just searching “lenses functional programming” in any search engine.
The idea is to have a data type (a Lens) that is generic and lets us get and set (a.k.a. zoom to) information on the type that the Lens is generic to.
Example:
struct Lens<Whole, Part> {
let get: (Whole) -> Part
let set: (Whole, Part) -> Whole
}
let personNameLens = Lens<Person, String> (
get: { $0.name },
set: { Person(name: $1, work: $0.work) }
)
personNameLens.get(joe) // Joe
personNameLens.set(joe, "Joe Wood").name // Joe Wood
That’s a Lens. However, we’ll only need a subset here, so let’s define a new data type that gives us only the set
method:
struct SetLens<Whole, Part> {
let set: (Whole, Part) -> Whole
}
To update a Person
instance, we can do this now:
let setPersonNameLens = SetLens<Person, String> (
set: { Person(name: $1, work: $0.work) }
}
setPersonNameLens.set(joe, "Joe Wood")
Now lets do a bit of work to move the interface up to type-level by making our SetLens
a static property of Person
, for brevity:
extension Person {
static let SetName = SetLens<Person, String> (
set: { Person(name: $1, work: $0.work) }
)
}
Person.SetName.set(joe, "Joe Wood")
We still have the problem that we’d have to interact with the SetLens
directly. To mimic the Elixir behaviour, we need to wrap the SetName
property on a static function that returns a function that when called, calls the set
method on the lens.
extension Person {
static func Update(name: String) -> Person -> Person {
return { p in SetName.set(p, newName) }
}
}
We define a static function that takes a new name as a parameter, and returns a function that takes a Person
and returns a Person
. Calling this function just passes the values to the SetLens
.
Now, let’s introduce the pipe operator:
precedencegroup Applicable {
associativity: left
}
infix operator |>
func |> <A, B>(a: A, rhs: (A) -> B) -> B {
return rhs(a)
}
This new custom operator takes a value to the left and a function on the right, and just calls the function on the right passing the value on the left. How convenient!
We can now do this:
joe |> Person.UpdateName("Joe Wood")
Ta’da!
Doing the appropriate amount of work, we could be writing this really soon:
joe
|> Person.Update(name: "Joe Wood")
|> Person.Update(work: Company(name: "Apple"))
And voilá, we’ve migrated one of Elixir’s core features to Swift, while maintaining type-safety!
Admittedly, it took a long of work just to migrate this one feature over to Swift. This does not mean, though, that it can’t be done for big code-bases and “real apps.” One of the best features of Swift is that the compiler is real smart and can tell us on compile-time if we messed something up. ❤️
This was just a small exercise, but I do appreciate the similarities that Swift and Elixir have, and the fact that both languages are flexbile enough that we can do these sort of things. Pretty cool.
Hey! I’m writing a book on best practices for iOS development with Swift, and it’s called (drum roll) Best Practices for Developing iOS Apps with Swift.
Subscribe below to get a 50% off coupon code when the book is released — also get the first chapter for free when it is ready!
If you come from the Objective-C world, you’re probably familiar with the singleton pattern.
@implementation MyClass
+ (id)sharedInstance
{
static MyClass *__instance = nil
static dispatch_once_t token;
dispatch_once(&token, ^{
__instance = [[MyClass alloc] init];
});
return __instance;
}
@end
Okay, here’s how you declare a singleton in Swift:
class MyClass {
static let sharedInstance = MyClass()
}
And that’s it.
Thanks to Swift’s immutability (using let
properties), we’re able to declare the static property on the type and have it resolve its value when the type declaration is first used.
Many say that singletons are an antipattern and should be avoided. I say that it depends. If you assess that a singleton is the right way to go to solve your current proble, go for it.
However, I should remind you that Swift is not Objective-C, and the fact that you can still use the same constructs that are used in Objective-C doesn’t mean you sould. Swift is a great language to exploit value semantics and immutability.
A couple of days ago, Apple published this post in which they describe some ways one can parse JSON using core languages of Swift 3.
Weird thing, they suggest that it is OK to have a type download JSON by itself:
You can create a type method on the
Restaurant
structure that translates a query method parameter into a corresponding request object and sends the HTTP request to the web service. This code would also be responsible for handling the response, deserializing the JSON data, creating Restaurant objects from each of the extracted dictionaries in the “results” array, and asynchronously returning them in a completion handler.
Please don’t do this. Having a type inflate itself from the network is just a cry for trouble.
One thing I did like of Apple’s post is that they put all of their custom code on an extension of the type they’re trying to add JSON support to. What I didn’t like, though, is that they’re relying in initializers that decide wether the type can be inflated or not.
I really don’t like that.
For me, the correct approach is to have a type method that validates wether the JSON is valid or not, and then return a type instance from that:
extension Restaurant {
static func with(json: [String:Any]) -> Restaurant? {
// Verify that the JSON contains the correct values, etc.
}
}
You could either return nil
there, or just throw
a custom error with the key that’s missing, as they do in their example.
Swift is a language that pushes us to think functionally, and in terms of values. The static method on the type is the correct approach, I think. It also feels cleaner.
In case you want to read my full take on how I think JSON should be handled with Swift 3, you can read this post.
Subscribe to get my updates on new products, tutorials, apps, and content you may be interested in.
I write about software development — mostly iOS and Elixir/Phoenix. If you like what I produce, subscribing is the best way to support what I do.
In case you didn’t know: I’m about to publish a book, check it out here. Subscribe on that page to get notified and get a 50% off coupon code when it launches.
Thanks in advance,
Oscar.
Hey there!
That’s right, I’m launching the first book in what I expect will be a long list of titles that I’ll be publishing in the following months.
Best Practices for Developing iOS Apps with Swift, available late October, focuses on how to avoid the mistakes that I’ve already made, so you don’t have to make them and your apps can be future-proof.
Register now to get get notified when the book launches. You’ll get the first chapter for free when it’s ready. Oh, also, a 50% off discount code on launch day.
Fun fact: this is actually the English version of the original book I wrote “Mejores Prácticas Del Desarrollo de Aplicaciones para iOS con Swift”, which is going to be out by the end of the month. If you’re interested, go check it out now.
Thanks for reading, and see you later!
As I’ve written before in this blog, I’ve been playing with Elixir/Phoenix for the past few months — I even have a couple of production applications running right now!
Just learned about Tesla, a new HTTP client for Elixir. I’ve taken a quick look at it and it seems that’s something I’ll be using for my next proyects.
What I like the most is the plug based architecture that it uses to build clients. It relfects a lot the way I build HTTP clients with Swift, so it feels right.
If you’re looking for a replacement for httpotion or httpoison, definitely take a look at this.
Just read this summary of Nate Taylor’s experience attending ElixirConf for the first time. So many details ring a bell on me, and I didn’t even attend the conference — but I sure wish I had.
By following the @ElixirStatus Twitter account I was able to get a sneek peak into the conference and it made me really regret not attending it. Maybe next year.
For now, I’ll just wait for the conference videos to be available.
This is sot-of a follow up to my last post, about self-referencing many_to_many
relationships using Ecto.
I find myself in a scenario where I have a User
:
# User model
defmodule MyApp.User do
use MyApp.Web, :model
alias MyApp.Contact
schema "users" do
has_many :_internal_contacts, MyApp.Contact
has_many :contacts, through: [:_internal_contacts, :contact]
timestamps
end
end
and an association model Contact
through which the User
has many contacts (User
instances):
defmodule MyApp.Contact do
use MyApp.Web, :model
alias MyApp.User
schema "contacts" do
field :status, :integer
belongs_to :user, User, foreign_key: :user_id
belongs_to :contact, User, foreign_key: :contact_id
timestamps
end
def status_code(status) do
case status do
:accepted ->
1
:pending ->
0
:rejected ->
-1
_ ->
0
end
end
I created an endpoint on my app that’s supposed to get me only the user’s contacts that have the :accepted
status (1). How can this be accomplished?
The Repo
module has a set of handy functions that let you preload associations on your models.
user = User |> Repo.get(1) |> Repo.preload(:contacts)
The above will preload all contacts
on the user. Pay attention to the fact that it is of type has_many
and it goes through the :_internal_contacts
property. This is the important cue.
Turns out that the preloads
parameter on Repo.preload/3
can be accompanied by a query.
import Ecto.Query
#1
query = from c in Contact, where: c.status == 1 and c.user_id == 1
u = User
|> Repo.get(1) #2
|> Repo.preload(_internal_contacts: query) #3
|> Repo.preload(:contacts) #4
The code above will:
Contact
s with status
1 and with user_id
1.User
instance._internal_contacts
on that instace using our query (these are Contact
instances, not User
instances):contacts
on our user. And since :contacts
goes through: _internal_contacts
, :contacts
has only valid contacts now (User
instances).Honestly, I don’t know if this is the right approach here (let me know!). I did find this thread on GitHub where the general issue that we’re facing here is described. It seems that there’s an interest to have the ability to filter the relationships on the declaration itself:
It would look something like this:
has_many :comments, MyApp.Comment, foreign_key: :commentable_id, fn (query) ->
from c in query, where: c.commentable_type == "articles"
end
However, right now, the saner approach seems to be the use of composable queries.
Have anything to add to this article or did I miss something? Please let me know on Twitter.