Mocking PHP with Swift

Since its release last year, Apple’s new programming language Swift has become pretty popular in the developer community. Swift modernizes the job of developing on Apple’s operating systems. Much like the Internet or Wikipedia, after less than a year using it I cannot remember how I used to code iOS apps without it.

Some of Swift’s best features (many of them borrowed from much praised languages like Python and Haskell) include generics, trailing closures, function currying, literal convertibles, and a very powerful operator overloading. These features let you substantially improve and extend the language as you code.

A side effect of some of these features is that you can kind of imitate other languages.

Here’s a somewhat creepy self-contained example of a PHP-style associative array constructor in Swift:

//SETUP
import Foundation
struct PHPArrayItem {
let key:String
let value:AnyObject
}
infix operator => { associativity left precedence 100 }
func => (left:String, right:AnyObject) -> PHPArrayItem {
return PHPArrayItem(key: left, value: right)
}
func array(elements:PHPArrayItem...) -> [String:AnyObject] {
var dict:[String:AnyObject] = [:]
elements.map{dict[$0.key] = $0.value}
return dict
}
//RESULT
//<?php lol
var myArray = array(
"a" => 1,
"b" => "foo",
"c" => "var",
"d" => 2
)
//?> This produces the dictionary ["a":1,"b":"foo","c":"var","d":2]

I’m only using one of the nice language features I mentioned before, but I can imagine how some of them may be used to similarly “mock” other languages or behaviours. JavaScript, you’re next! This may actually get useful!

Originally written for relevant.ai

Like what you read? Give Adolfo Rodriguez a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.