Skip to content

Instantly share code, notes, and snippets.

@gowrishankarin
Created January 6, 2015 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gowrishankarin/ba706342bd4f1469c6f4 to your computer and use it in GitHub Desktop.
Save gowrishankarin/ba706342bd4f1469c6f4 to your computer and use it in GitHub Desktop.
My first program in Apple Swift
// 1. Structure declaration
// 2. Enum declartion
// 3. Structure variables declaration
struct HTTPRequest {
enum Method {
case GET
case POST
}
// Type Specific variable
var path: String
// Enumeration instance
var method: Method
}
// 4. Abstract base class or virtual class
protocol HTTPHandlerType {
// ** Not sure what it is.
typealias Data
func handle(request: HTTPRequest, data: Data) -> Bool
}
// 5. Class declaration
class HTTPServer {
// 6. Abstract function signature, If you understand this line of code in first glance u r thru for generics.
func addHandler<T: HTTPHandlerType>(handler: T) {
// Populating values for an array. Absolutely cluess what is going on in the lines marked "holy shit"
handlers.append {
// HOLY SHIT
(request: HTTPRequest, args: Any) -> Bool in
// HOLY SHIT
if let typedArgs = args as? T.Data {
return handler.handle(request, data: typedArgs)
}
return false
}
}
// 7. Array of tuple declaration I guess and initialization using []. Is it tuple, not quite sure. Is it array of function pointer
private var handlers: [(HTTPRequest, Any) -> Bool] = []
// 8. Function signature with Bool return type
func dispatch(req: HTTPRequest, args: Any) -> Bool {
for handler in handlers {
// here it looks like function pointer
if handler (req, args) {
return true
}
}
return false;
}
}
// 9. Derived class
class MyHandler: HTTPHandlerType {
// 10. Pure virtual(abstract) function implementation
func handle(request: HTTPRequest, data: Int) -> Bool {
return data > 5
}
}
// 11. Object instance without new operator. Declare constants with let and variables with var
let server = HTTPServer()
server.addHandler(MyHandler())
server.dispatch(HTTPRequest(path: "/update", method: .POST), args: "x")
// 12. HIGHT OF MADNESS, UNICODE SUPPORT. People will declare variables in their local languages
let 你好 = "你好世界"
let சந்தோஷ் = "சந்தோஷ்"
var అజయ్ = "అజయ్"
var હાર્દિક = "હાર્દિક"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment