Просмотр исходного кода

Swifter ready for new toolchain swift-DEVELOPMENT-SNAPSHOT-2016-03-16-a-osx.

Damian Kołakowski 10 лет назад
Родитель
Сommit
45c4274342

+ 3 - 4
Sources/App.swift

@@ -25,15 +25,14 @@ public class App {
         
         // Watch process signals.
         
-        Process.watchSignals { signal in
-            switch signal {
+        Process.watchSignals { switch $0 {
             case SIGTERM, SIGINT:
                 self.server.stop()
                 DatabaseReflection.sharedDatabase?.close()
                 exit(EXIT_SUCCESS)
             case SIGINFO:
                 print("Swifter Version: \(HttpServer.VERSION)")
-                print(self.server.routes.joinWithSeparator("\n"))
+                print(self.server.routes.joined(separator: "\n"))
             case SIGHUP:
                 print("//TODO - Reload config.")
             default:
@@ -56,6 +55,6 @@ public class App {
         
         print("Server started. Waiting for requests....")
         
-        NSRunLoop.mainRunLoop().run()
+        NSRunLoop.main().run()
     }
 }

+ 3 - 3
Sources/DemoServer.swift

@@ -50,7 +50,7 @@ public func demoServer(publicDir: String) -> HttpServer {
     
     server.GET["/upload"] = { r in
         if let html = NSData(contentsOfFile:"\(publicDir)/file.html") {
-            var array = [UInt8](count: html.length, repeatedValue: 0)
+            var array = [UInt8](repeating: 0, count: html.length)
             html.getBytes(&array, length: html.length)
             return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
         }
@@ -67,7 +67,7 @@ public func demoServer(publicDir: String) -> HttpServer {
     
     server.GET["/login"] = { r in
         if let html = NSData(contentsOfFile:"\(publicDir)/login.html") {
-            var array = [UInt8](count: html.length, repeatedValue: 0)
+            var array = [UInt8](repeating: 0, count: html.length)
             html.getBytes(&array, length: html.length)
             return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
         }
@@ -76,7 +76,7 @@ public func demoServer(publicDir: String) -> HttpServer {
     
     server.POST["/login"] = { r in
         let formFields = r.parseUrlencodedForm()
-        return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joinWithSeparator("<br>")))
+        return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
     }
     
     server["/demo"] = { r in

+ 3 - 6
Sources/File.swift

@@ -11,7 +11,7 @@
     import Foundation
 #endif
 
-public enum FileError: ErrorType {
+public enum FileError: ErrorProtocol {
     case OpenFailed(String)
     case WriteFailed(String)
     case ReadFailed(String)
@@ -55,10 +55,7 @@ public class File {
         if path == nil {
             throw FileError.GetCurrentWorkingDirectoryFailed(descriptionOfLastError())
         }
-        guard let result = String.fromCString(path) else {
-            throw FileError.GetCurrentWorkingDirectoryFailed("Could not convert getcwd(...)'s result (\(path)) to String.")
-        }
-        return result
+        return String(cString: path)
     }
     
     private let pointer: UnsafeMutablePointer<FILE>
@@ -106,7 +103,7 @@ public class File {
     }
     
     private static func descriptionOfLastError() -> String {
-        return String.fromCString(UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
+        return String(cString: UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
     }
 }
 

+ 10 - 10
Sources/HttpHandlers+Files.swift

@@ -19,7 +19,7 @@ extension HttpHandlers {
                 return .NotFound
             }
             return .RAW(200, "OK", [:], { writer in
-                var buffer = [UInt8](count: 64, repeatedValue: 0)
+                var buffer = [UInt8](repeating: 0, count: 64)
                 while let count = try? file.read(&buffer) where count > 0 {
                     writer.write(buffer[0..<count])
                 }
@@ -52,7 +52,7 @@ extension HttpHandlers {
                 #if os(Linux)
                     let rangeString = rangeHeader.substringFromIndex(HttpHandlers.rangePrefix.characters.count)
                 #else
-                    let rangeString = rangeHeader.substringFromIndex(rangeHeader.startIndex.advancedBy(HttpHandlers.rangePrefix.characters.count))
+                    let rangeString = rangeHeader.substring(from: rangeHeader.startIndex.advanced(by: HttpHandlers.rangePrefix.characters.count))
                 #endif
                 
                 let rangeStringExploded = rangeString.split("-")
@@ -65,7 +65,7 @@ extension HttpHandlers {
                 let endStr   = rangeStringExploded[1]
                 
                 guard let start = Int(startStr), end = Int(endStr) else {
-                    var array = [UInt8](count: fileBody.length, repeatedValue: 0)
+                    var array = [UInt8](repeating: 0, count: fileBody.length)
                     fileBody.getBytes(&array, length: fileBody.length)
                     return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
                 }
@@ -77,15 +77,15 @@ extension HttpHandlers {
                     return HttpResponse.RAW(416, "Requested range not satisfiable", nil, nil)
                 }
                 
-                let chunk = fileBody.subdataWithRange(chunkRange)
+                let chunk = fileBody.subdata(with: chunkRange)
                 
                 let headers = [ "Content-Range" : "bytes \(startStr)-\(endStr)/\(fileBody.length)" ]
                 
-                var content = [UInt8](count: chunk.length, repeatedValue: 0)
+                var content = [UInt8](repeating: 0, count: chunk.length)
                 chunk.getBytes(&content, length: chunk.length)
                 return HttpResponse.RAW(206, "Partial Content", headers, { $0.write(content) })
             } else {
-                var content = [UInt8](count: fileBody.length, repeatedValue: 0)
+                var content = [UInt8](repeating: 0, count: fileBody.length)
                 fileBody.getBytes(&content, length: fileBody.length)
                 return HttpResponse.RAW(200, "OK", nil, { $0.write(content) })
             }
@@ -100,14 +100,14 @@ extension HttpHandlers {
             let filePath = dir + "/" + value
             let fileManager = NSFileManager.defaultManager()
             var isDir: ObjCBool = false
-            guard fileManager.fileExistsAtPath(filePath, isDirectory: &isDir) else {
+            guard fileManager.fileExists(atPath: filePath, isDirectory: &isDir) else {
                 return HttpResponse.NotFound
             }
             if isDir {
                 do {
-                    let files = try fileManager.contentsOfDirectoryAtPath(filePath)
+                    let files = try fileManager.contentsOfDirectory(atPath: filePath)
                     var response = "<h3>\(filePath)</h3></br><table>"
-                    response += files.map({ "<tr><td><a href=\"\(r.path)/\($0)\">\($0)</a></td></tr>"}).joinWithSeparator("")
+                    response += files.map({ "<tr><td><a href=\"\(r.path)/\($0)\">\($0)</a></td></tr>"}).joined(separator: "")
                     response += "</table>"
                     return HttpResponse.OK(.Html(response))
                 } catch {
@@ -115,7 +115,7 @@ extension HttpHandlers {
                 }
             } else {
                 if let content = NSData(contentsOfFile: filePath) {
-                    var array = [UInt8](count: content.length, repeatedValue: 0)
+                    var array = [UInt8](repeating: 0, count: content.length)
                     content.getBytes(&array, length: content.length)
                     return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
                 }

+ 1 - 1
Sources/HttpHandlers+WebSockets.swift

@@ -46,7 +46,7 @@ extension HttpHandlers {
     
     public class WebSocketSession {
         
-        public enum Error: ErrorType { case UnknownOpCode(String), UnMaskedFrame }
+        public enum Error: ErrorProtocol { case UnknownOpCode(String), UnMaskedFrame }
         public enum OpCode { case Continue, Close, Ping, Pong, Text, Binary }
         
         public class Frame {

+ 2 - 2
Sources/HttpParser.swift

@@ -11,7 +11,7 @@
     import Foundation
 #endif
 
-enum HttpParserError: ErrorType {
+enum HttpParserError: ErrorProtocol {
     case InvalidStatusLine(String)
 }
 
@@ -64,7 +64,7 @@ public class HttpParser {
             }
             let headerTokens = headerLine.split(1, separator: ":")
             if let name = headerTokens.first, value = headerTokens.last {
-                headers[name.lowercaseString] = value.trim()
+                headers[name.lowercased()] = value.trim()
             }
         } while true
     }

+ 7 - 7
Sources/HttpRequest.swift

@@ -21,7 +21,7 @@ public class HttpRequest {
         guard let headerValue = headers[headerName] else {
             return false
         }
-        return headerValue.split(",").filter({ $0.trim().lowercaseString == token }).count > 0
+        return headerValue.split(",").filter({ $0.trim().lowercased() == token }).count > 0
     }
     
     public func parseUrlencodedForm() -> [(String, String)] {
@@ -94,7 +94,7 @@ public class HttpRequest {
     }
     
     private func parseMultiPartFormData(data: [UInt8], boundary: String) -> [MultiPart] {
-        var generator = data.generate()
+        var generator = data.makeIterator()
         var result = [MultiPart]()
         while let part = nextMultiPart(&generator, boundary: boundary, isFirst: result.isEmpty) {
             result.append(part)
@@ -102,7 +102,7 @@ public class HttpRequest {
         return result
     }
     
-    private func nextMultiPart(generator: inout IndexingGenerator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
+    private func nextMultiPart(generator: inout IndexingIterator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
         if isFirst {
             guard nextMultiPartLine(&generator) == boundary else {
                 return nil
@@ -114,7 +114,7 @@ public class HttpRequest {
         while let line = nextMultiPartLine(&generator) where !line.isEmpty {
             let tokens = line.split(":")
             if let name = tokens.first, value = tokens.last where tokens.count == 2 {
-                headers[name.lowercaseString] = value.trim()
+                headers[name.lowercased()] = value.trim()
             }
         }
         guard let body = nextMultiPartBody(&generator, boundary: boundary) else {
@@ -123,7 +123,7 @@ public class HttpRequest {
         return MultiPart(headers: headers, body: body)
     }
     
-    private func nextMultiPartLine(generator: inout IndexingGenerator<[UInt8]>) -> String? {
+    private func nextMultiPartLine(generator: inout IndexingIterator<[UInt8]>) -> String? {
         var result = String()
         while let value = generator.next() {
             if value > HttpRequest.CR {
@@ -139,7 +139,7 @@ public class HttpRequest {
     static let CR = UInt8(13)
     static let NL = UInt8(10)
     
-    private func nextMultiPartBody(generator: inout IndexingGenerator<[UInt8]>, boundary: String) -> [UInt8]? {
+    private func nextMultiPartBody(generator: inout IndexingIterator<[UInt8]>, boundary: String) -> [UInt8]? {
         var body = [UInt8]()
         let boundaryArray = [UInt8](boundary.utf8)
         var matchOffset = 0;
@@ -147,7 +147,7 @@ public class HttpRequest {
             matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
             body.append(x)
             if matchOffset == boundaryArray.count {
-                body.removeRange(Range<Int>(body.count-matchOffset ..< body.count))
+                body.removeSubrange(Range<Int>(body.count-matchOffset ..< body.count))
                 if body.last == HttpRequest.NL {
                     body.removeLast()
                     if body.last == HttpRequest.CR {

+ 2 - 2
Sources/HttpResponse.swift

@@ -7,7 +7,7 @@
 
 import Foundation
 
-public enum SerializationError: ErrorType {
+public enum SerializationError: ErrorProtocol {
     case InvalidObject
     case NotSupported
 }
@@ -31,7 +31,7 @@ public enum HttpResponseBody {
                 guard NSJSONSerialization.isValidJSONObject(object) else {
                     throw SerializationError.InvalidObject
                 }
-                let json = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted)
+                let json = try NSJSONSerialization.data(withJSONObject: object, options: NSJSONWritingOptions.prettyPrinted)
                 let data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
                 return (data.count, {
                     $0.write(data)

+ 10 - 10
Sources/HttpRouter.swift

@@ -19,7 +19,7 @@ public class HttpRouter {
     public func routes() -> [String] {
         var routes = [String]()
         for (_, child) in rootNode.nodes {
-            routes.appendContentsOf(routesForNode(child));
+            routes.append(contentsOf: routesForNode(child));
         }
         return routes
     }
@@ -30,7 +30,7 @@ public class HttpRouter {
             result.append(prefix)
         }
         for (key, child) in node.nodes {
-            result.appendContentsOf(routesForNode(child, prefix: prefix + "/" + key));
+            result.append(contentsOf: routesForNode(child, prefix: prefix + "/" + key));
         }
         return result
     }
@@ -38,25 +38,25 @@ public class HttpRouter {
     public func register(method: String?, path: String, handler: (HttpRequest -> HttpResponse)?) {
         var pathSegments = stripQuery(path).split("/")
         if let method = method {
-            pathSegments.insert(method, atIndex: 0)
+            pathSegments.insert(method, at: 0)
         } else {
-            pathSegments.insert("*", atIndex: 0)
+            pathSegments.insert("*", at: 0)
         }
-        var pathSegmentsGenerator = pathSegments.generate()
+        var pathSegmentsGenerator = pathSegments.makeIterator()
         inflate(&rootNode, generator: &pathSegmentsGenerator).handler = handler
     }
     
     public func route(method: String?, path: String) -> ([String: String], HttpRequest -> HttpResponse)? {
         if let method = method {
             let pathSegments = (method + "/" + stripQuery(path)).split("/")
-            var pathSegmentsGenerator = pathSegments.generate()
+            var pathSegmentsGenerator = pathSegments.makeIterator()
             var params = [String:String]()
             if let handler = findHandler(&rootNode, params: &params, generator: &pathSegmentsGenerator) {
                 return (params, handler)
             }
         }
         let pathSegments = ("*/" + stripQuery(path)).split("/")
-        var pathSegmentsGenerator = pathSegments.generate()
+        var pathSegmentsGenerator = pathSegments.makeIterator()
         var params = [String:String]()
         if let handler = findHandler(&rootNode, params: &params, generator: &pathSegmentsGenerator) {
             return (params, handler)
@@ -64,7 +64,7 @@ public class HttpRouter {
         return nil
     }
     
-    private func inflate(node: inout Node, generator: inout IndexingGenerator<[String]>) -> Node {
+    private func inflate(node: inout Node, generator: inout IndexingIterator<[String]>) -> Node {
         if let pathSegment = generator.next() {
             if let _ = node.nodes[pathSegment] {
                 return inflate(&node.nodes[pathSegment]!, generator: &generator)
@@ -76,7 +76,7 @@ public class HttpRouter {
         return node
     }
     
-    private func findHandler(node: inout Node, params: inout [String: String], generator: inout IndexingGenerator<[String]>) -> (HttpRequest -> HttpResponse)? {
+    private func findHandler(node: inout Node, params: inout [String: String], generator: inout IndexingIterator<[String]>) -> (HttpRequest -> HttpResponse)? {
         guard let pathToken = generator.next() else {
             return node.handler
         }
@@ -85,7 +85,7 @@ public class HttpRouter {
             if variableNode.1.nodes.count == 0 {
                 // if it's the last element of the pattern and it's a variable, stop the search and
                 // append a tail as a value for the variable.
-                let tail = generator.joinWithSeparator("/")
+                let tail = generator.joined(separator: "/")
                 if tail.utf8.count > 0 {
                     params[variableNode.0] = pathToken + "/" + tail
                 } else {

+ 1 - 1
Sources/HttpServerIO.swift

@@ -47,7 +47,7 @@ public class HttpServerIO {
             for socket in self.clientSockets {
                 socket.shutdwn()
             }
-            self.clientSockets.removeAll(keepCapacity: true)
+            self.clientSockets.removeAll(keepingCapacity: true)
         }
     }
     

+ 7 - 4
Sources/Reflection.swift

@@ -29,7 +29,7 @@ public extension DatabaseReflectionProtocol {
         let reflections = _reflect(self)
         
         var fields = [String: Any?]()
-        for index in 0.stride(to: reflections.count, by: 1) {
+        for index in stride(from: 0, to: reflections.count, by: 1) {
             let reflection = reflections[index]
             fields[reflection.0] = reflection.1.value
         }
@@ -50,6 +50,7 @@ public extension DatabaseReflectionProtocol {
     
     public func schemeWithValuesAsString() -> (String, [(String, String?)]) {
         let (name, fields) = schemeWithValuesMethod2()
+        let (_, _) = schemeWithValuesMethod1()
         var map = [(String, String?)]()
         for (key, value) in fields {
             // TODO - Replace this by extending all supported types by a protocol.
@@ -61,6 +62,8 @@ public extension DatabaseReflectionProtocol {
             if let stringValue = value as? String { map.append((key, stringValue)) }
         }
         return (name, map)
+        
+
     }
     
     public static func classInstanceWithSchemeMethod1() -> (Self, String, [String: Any?]) {
@@ -86,9 +89,9 @@ public extension DatabaseReflectionProtocol {
             throw SQLiteError.OpenFailed("Database connection is not opened.")
         }
         let (name, fields) = schemeWithValuesAsString()
-        try database.exec("CREATE TABLE IF NOT EXISTS \(name) (" + fields.map { "\($0.0) TEXT" }.joinWithSeparator(", ")  + ");")
-        let names = fields.map { "\($0.0)" }.joinWithSeparator(", ")
-        let values = Array(count: fields.count, repeatedValue: "?").joinWithSeparator(", ")
+        try database.exec("CREATE TABLE IF NOT EXISTS \(name) (" + fields.map { "\($0.0) TEXT" }.joined(separator: ", ")  + ");")
+        let names = fields.map { "\($0.0)" }.joined(separator: ", ")
+        let values = Array(repeating: "?", count: fields.count).joined(separator: ", ")
         try database.exec("INSERT INTO \(name)(" + names + ") VALUES(" + values  + ");", fields.map { $0.1 })
     }
     

+ 28 - 30
Sources/SQLite.swift

@@ -7,7 +7,7 @@
 
 import Foundation
 
-public enum SQLiteError: ErrorType {
+public enum SQLiteError: ErrorProtocol {
     case OpenFailed(String?)
     case ExecFailed(String?)
     case BindFailed(String?)
@@ -15,18 +15,18 @@ public enum SQLiteError: ErrorType {
 
 public class SQLite {
     
-    private let databaseConnection: COpaquePointer
+    private let databaseConnection: OpaquePointer
     
     public static func open(path: String) throws -> SQLite {
-        var databaseConnection = COpaquePointer()
+        var databaseConnection: OpaquePointer = nil
         let openResult = path.withCString { sqlite3_open($0, &databaseConnection) }
         guard openResult == SQLITE_OK else {
-            throw SQLiteError.OpenFailed(String.fromCString(sqlite3_errmsg(databaseConnection)))
+            throw SQLiteError.OpenFailed(String(cString: sqlite3_errmsg(databaseConnection)))
         }
         return SQLite(databaseConnection)
     }
     
-    private init(_ databaseConnection: COpaquePointer) {
+    private init(_ databaseConnection: OpaquePointer) {
         self.databaseConnection = databaseConnection
     }
     
@@ -37,16 +37,16 @@ public class SQLite {
     }
     
     public func exec(sql: String, _ params: [String?]? = nil, _ step: ([String: String?] -> Void)? = nil) throws {
-        var statement = COpaquePointer()
+        var statement: OpaquePointer = nil
         let prepareResult = sql.withCString { sqlite3_prepare_v2(databaseConnection, $0, Int32(sql.utf8.count), &statement, nil) }
         guard prepareResult == SQLITE_OK else {
-            throw SQLiteError.ExecFailed(String.fromCString(sqlite3_errmsg(databaseConnection)))
+            throw SQLiteError.ExecFailed(String(cString: sqlite3_errmsg(databaseConnection)))
         }
-        for (index, value) in (params ?? [String?]()).enumerate() {
+        for (index, value) in (params ?? [String?]()).enumerated() {
             let bindResult = value?.withCString({ sqlite3_bind_text(statement, index + 1, $0, -1 /* take zero terminator. */) { _ in } })
                     ?? sqlite3_bind_null(statement, index + 1)
             guard bindResult == SQLITE_OK else {
-                throw SQLiteError.BindFailed(String.fromCString(sqlite3_errmsg(databaseConnection)))
+                throw SQLiteError.BindFailed(String(cString: sqlite3_errmsg(databaseConnection)))
             }
         }
         while true {
@@ -55,13 +55,12 @@ public class SQLite {
             case SQLITE_ROW:
                 var content = [String: String?]()
                 for i in 0..<sqlite3_column_count(statement) {
-                    if let name = String.fromCString(UnsafePointer<CChar>(sqlite3_column_name(statement, i))) {
-                        let pointer = sqlite3_column_text(statement, i)
-                        if pointer == nil {
-                            content[name] = nil
-                        } else {
-                            content[name] = String.fromCString(UnsafePointer<CChar>(pointer))
-                        }
+                    let name = String(cString: UnsafePointer<CChar>(sqlite3_column_name(statement, i)))
+                    let pointer = sqlite3_column_text(statement, i)
+                    if pointer == nil {
+                        content[name] = nil
+                    } else {
+                        content[name] = String(cString: UnsafePointer<CChar>(pointer))
                     }
                 }
                 step?(content)
@@ -77,30 +76,29 @@ public class SQLite {
     
     
     public func enumerate(sql: String) throws -> StatmentSequence {
-        var statement = COpaquePointer()
+        var statement: OpaquePointer = nil
         let prepareResult = sql.withCString { sqlite3_prepare_v2(databaseConnection, $0, Int32(sql.utf8.count), &statement, nil) }
         guard prepareResult == SQLITE_OK else {
-            throw SQLiteError.ExecFailed(String.fromCString(sqlite3_errmsg(databaseConnection)))
+            throw SQLiteError.ExecFailed(String(cString: sqlite3_errmsg(databaseConnection)))
         }
         return StatmentSequence(statement: statement)
     }
     
-    public struct StatmentGenerator: GeneratorType {
+    public struct StatmentGenerator: IteratorProtocol {
         
-        public let statement: COpaquePointer
+        public let statement: OpaquePointer
         
         public func next() -> [String: String]? {
             switch sqlite3_step(statement) {
             case SQLITE_ROW:
                 var content = [String: String]()
                 for i in 0..<sqlite3_column_count(statement) {
-                    if let name = String.fromCString(UnsafePointer<CChar>(sqlite3_column_name(statement, i))) {
-                        let pointer = sqlite3_column_text(statement, i)
-                        if pointer == nil {
-                            content[name] = nil
-                        } else {
-                            content[name] = String.fromCString(UnsafePointer<CChar>(pointer))
-                        }
+                    let name = String(cString: UnsafePointer<CChar>(sqlite3_column_name(statement, i)))
+                    let pointer = sqlite3_column_text(statement, i)
+                    if pointer == nil {
+                        content[name] = nil
+                    } else {
+                        content[name] = String(cString: UnsafePointer<CChar>(pointer))
                     }
                 }
                 return content
@@ -111,11 +109,11 @@ public class SQLite {
         }
     }
     
-    public struct StatmentSequence: SequenceType {
+    public struct StatmentSequence: Sequence {
         
-        public let statement: COpaquePointer
+        public let statement: OpaquePointer
         
-        public func generate() -> StatmentGenerator {
+        public func makeIterator() -> StatmentGenerator {
             return StatmentGenerator(statement: statement)
         }
     }

+ 5 - 8
Sources/Socket.swift

@@ -13,7 +13,7 @@
 
 /* Low level routines for POSIX sockets */
 
-public enum SocketError: ErrorType {
+public enum SocketError: ErrorProtocol {
     case SocketCreationFailed(String)
     case SocketSettingReUseAddrFailed(String)
     case BindFailed(String)
@@ -133,7 +133,7 @@ public class Socket: Hashable, Equatable {
     }
     
     public func read() throws -> UInt8 {
-        var buffer = [UInt8](count: 1, repeatedValue: 0)
+        var buffer = [UInt8](repeating: 0, count: 1)
         let next = recv(self.socketFileDescriptor as Int32, &buffer, Int(buffer.count), 0)
         if next <= 0 {
             throw SocketError.RecvFailed(Socket.descriptionOfLastError())
@@ -159,18 +159,15 @@ public class Socket: Hashable, Equatable {
         if getpeername(self.socketFileDescriptor, &addr, &len) != 0 {
             throw SocketError.GetPeerNameFailed(Socket.descriptionOfLastError())
         }
-        var hostBuffer = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
+        var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
         if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
             throw SocketError.GetNameInfoFailed(Socket.descriptionOfLastError())
         }
-        guard let name = String.fromCString(hostBuffer) else {
-            throw SocketError.ConvertingPeerNameFailed
-        }
-        return name
+        return String(cString: hostBuffer)
     }
     
     private class func descriptionOfLastError() -> String {
-        return String.fromCString(UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
+        return String(cString: UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
     }
     
     private class func setNoSigPipe(socket: Int32) {

+ 3 - 3
Sources/String+BASE64.swift

@@ -22,7 +22,7 @@ extension String {
         
         var result = [UInt8]()
         var tmp: UInt8
-        for index in 0.stride(to: data.count, by: 3) {
+        for index in stride(from: 0, to: data.count, by: 3) {
             let byte = data[index]
             tmp = (byte & 0xFC) >> 2;
             result.append(CODES[Int(tmp)])
@@ -38,11 +38,11 @@ extension String {
                     result.append(CODES[Int(tmp)]);
                 } else  {
                     result.append(CODES[Int(tmp)]);
-                    result.appendContentsOf([UInt8]("=".utf8));
+                    result.append(contentsOf: [UInt8]("=".utf8));
                 }
             } else {
                 result.append(CODES[Int(tmp)]);
-                result.appendContentsOf([UInt8]("==".utf8));
+                result.append(contentsOf: [UInt8]("==".utf8));
             }
         }
         return String.fromUInt8(result)

+ 4 - 4
Sources/String+Misc.swift

@@ -18,7 +18,7 @@ extension String {
     }
     
     public func split(maxSplit: Int = Int.max, separator: Character) -> [String] {
-        return self.characters.split(maxSplit) { $0 == separator }.map(String.init)
+        return self.characters.split(maxSplits: maxSplit, omittingEmptySubsequences: true) { $0 == separator }.map(String.init)
     }
     
     public func replace(old: Character, _ new: Character) -> String {
@@ -61,7 +61,7 @@ extension String {
                     decodeBuffer.append(first*16+secon)
                 } else {
                     if !decodeBuffer.isEmpty {
-                        output.appendContentsOf(String.fromUInt8(decodeBuffer))
+                        output.append(String.fromUInt8(decodeBuffer))
                         decodeBuffer.removeAll()
                     }
                     if let first = first { output.append(Character(first)) }
@@ -69,14 +69,14 @@ extension String {
                 }
             } else {
                 if !decodeBuffer.isEmpty {
-                    output.appendContentsOf(String.fromUInt8(decodeBuffer))
+                    output.append(String.fromUInt8(decodeBuffer))
                     decodeBuffer.removeAll()
                 }
                 output.append(Character(scalar))
             }
         }
         if !decodeBuffer.isEmpty {
-            output.appendContentsOf(String.fromUInt8(decodeBuffer))
+            output.append(String.fromUInt8(decodeBuffer))
             decodeBuffer.removeAll()
         }
         return output

+ 3 - 3
Sources/String+SHA1.swift

@@ -42,14 +42,14 @@ extension String {
         
         let padBytesCount = ( message.count + 8 ) % 64
         
-        message.appendContentsOf([UInt8](count: 64 - padBytesCount, repeatedValue: 0))
+        message.append(contentsOf: [UInt8](repeating: 0, count: 64 - padBytesCount))
         
         // append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
         
         var mlBigEndian = ml.bigEndian
         let bytePtr = withUnsafePointer(&mlBigEndian) { UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: sizeofValue(mlBigEndian)) }
         
-        message.appendContentsOf(Array(bytePtr))
+        message.append(contentsOf: Array(bytePtr))
         
         // Process the message in successive 512-bit chunks ( 64 bytes chunks ):
 
@@ -60,7 +60,7 @@ extension String {
             // break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15
             
             for i in 0...15 {
-                let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>($0.baseAddress + (i*4)).memory })
+                let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>($0.baseAddress + (i*4)).pointee})
                 words.append(value.bigEndian)
             }
             

+ 0 - 4
Swifter.xcodeproj/project.pbxproj

@@ -31,7 +31,6 @@
 		7C5915231C92A99300D884BC /* SwifterTestsReflection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C5915211C92A99300D884BC /* SwifterTestsReflection.swift */; };
 		7C71C5B01A1D52F800682BF0 /* login.html in CopyFiles */ = {isa = PBXBuildFile; fileRef = 98630C061A1C9A9D00478D08 /* login.html */; };
 		7C71C5B11A1EC49B00682BF0 /* logo.png in CopyFiles */ = {isa = PBXBuildFile; fileRef = 7CB102DF1A17381D00CBA3B4 /* logo.png */; };
-		7C73C6911C2615FE00AEF6CA /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18E610A51BD6397D00B7D17A /* SwiftyJSON.swift */; };
 		7C73C6921C26179C00AEF6CA /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CDAB80C1BE2A1D400C8A977 /* AppDelegate.swift */; };
 		7C73C6AA1C261A2100AEF6CA /* DemoServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C73C6941C2619E100AEF6CA /* DemoServer.swift */; };
 		7C73C6AB1C261A2100AEF6CA /* HttpHandlers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C73C6951C2619E100AEF6CA /* HttpHandlers.swift */; };
@@ -182,7 +181,6 @@
 /* End PBXCopyFilesBuildPhase section */
 
 /* Begin PBXFileReference section */
-		18E610A51BD6397D00B7D17A /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyJSON.swift; sourceTree = "<group>"; };
 		7AE893E71C05127900A29F63 /* Swifter.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Swifter.framework; sourceTree = BUILT_PRODUCTS_DIR; };
 		7AE893E91C05127900A29F63 /* SwifteriOS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwifteriOS.h; sourceTree = "<group>"; };
 		7AE893EB1C05127900A29F63 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
@@ -364,7 +362,6 @@
 		7CA4813C19A2EA8D0030B30D /* SwifterSampleOSX */ = {
 			isa = PBXGroup;
 			children = (
-				18E610A51BD6397D00B7D17A /* SwiftyJSON.swift */,
 				7CA4813D19A2EA8D0030B30D /* main.swift */,
 			);
 			path = SwifterSampleOSX;
@@ -863,7 +860,6 @@
 				7CBFA0151C9347A7000989AB /* String+BASE64.swift in Sources */,
 				7CBFA0161C9347A7000989AB /* Reflection.swift in Sources */,
 				7CBFA0171C9347A7000989AB /* SQLite.swift in Sources */,
-				7C73C6911C2615FE00AEF6CA /* SwiftyJSON.swift in Sources */,
 				7CA4813E19A2EA8D0030B30D /* main.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;

+ 0 - 1352
SwifterSampleOSX/SwiftyJSON.swift

@@ -1,1352 +0,0 @@
-//  SwiftyJSON.swift
-//
-//  Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
-//
-//  Permission is hereby granted, free of charge, to any person obtaining a copy
-//  of this software and associated documentation files (the "Software"), to deal
-//  in the Software without restriction, including without limitation the rights
-//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-//  copies of the Software, and to permit persons to whom the Software is
-//  furnished to do so, subject to the following conditions:
-//
-//  The above copyright notice and this permission notice shall be included in
-//  all copies or substantial portions of the Software.
-//
-//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-//  THE SOFTWARE.
-
-import Foundation
-
-// MARK: - Error
-
-///Error domain
-public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
-
-///Error code
-public let ErrorUnsupportedType: Int! = 999
-public let ErrorIndexOutOfBounds: Int! = 900
-public let ErrorWrongType: Int! = 901
-public let ErrorNotExist: Int! = 500
-public let ErrorInvalidJSON: Int! = 490
-
-// MARK: - JSON Type
-
-/**
-JSON's type definitions.
-
-See http://tools.ietf.org/html/rfc7231#section-4.3
-*/
-public enum Type :Int{
-    
-    case Number
-    case String
-    case Bool
-    case Array
-    case Dictionary
-    case Null
-    case Unknown
-}
-
-// MARK: - JSON Base
-
-public struct JSON {
-    
-    /**
-    Creates a JSON using the data.
-    
-    - parameter data:  The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
-    - parameter opt:   The JSON serialization reading options. `.AllowFragments` by default.
-    - parameter error: error The NSErrorPointer used to return the error. `nil` by default.
-    
-    - returns: The created JSON
-    */
-    public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
-        do {
-            let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
-            self.init(object)
-        } catch let aError as NSError {
-            if error != nil {
-                error.memory = aError
-            }
-            self.init(NSNull())
-        }
-    }
-    
-    /**
-    Creates a JSON using the object.
-    
-    - parameter object:  The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
-    
-    - returns: The created JSON
-    */
-    public init(_ object: AnyObject) {
-        self.object = object
-    }
-    
-    /**
-    Creates a JSON from a [JSON]
-    
-    - parameter jsonArray: A Swift array of JSON objects
-    
-    - returns: The created JSON
-    */
-    public init(_ jsonArray:[JSON]) {
-        self.init(jsonArray.map { $0.object })
-    }
-    
-    /**
-    Creates a JSON from a [String: JSON]
-    
-    - parameter jsonDictionary: A Swift dictionary of JSON objects
-    
-    - returns: The created JSON
-    */
-    public init(_ jsonDictionary:[String: JSON]) {
-        var dictionary = [String: AnyObject]()
-        for (key, json) in jsonDictionary {
-            dictionary[key] = json.object
-        }
-        self.init(dictionary)
-    }
-    
-    /// Private object
-    private var rawArray: [AnyObject] = []
-    private var rawDictionary: [String : AnyObject] = [:]
-    private var rawString: String = ""
-    private var rawNumber: NSNumber = 0
-    private var rawNull: NSNull = NSNull()
-    /// Private type
-    private var _type: Type = .Null
-    /// prviate error
-    private var _error: NSError? = nil
-    
-    /// Object in JSON
-    public var object: AnyObject {
-        get {
-            switch self.type {
-            case .Array:
-                return self.rawArray
-            case .Dictionary:
-                return self.rawDictionary
-            case .String:
-                return self.rawString
-            case .Number:
-                return self.rawNumber
-            case .Bool:
-                return self.rawNumber
-            default:
-                return self.rawNull
-            }
-        }
-        set {
-            _error = nil
-            switch newValue {
-            case let number as NSNumber:
-                if number.isBool {
-                    _type = .Bool
-                } else {
-                    _type = .Number
-                }
-                self.rawNumber = number
-            case  let string as String:
-                _type = .String
-                self.rawString = string
-            case  _ as NSNull:
-                _type = .Null
-            case let array as [AnyObject]:
-                _type = .Array
-                self.rawArray = array
-            case let dictionary as [String : AnyObject]:
-                _type = .Dictionary
-                self.rawDictionary = dictionary
-            default:
-                _type = .Unknown
-                _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
-            }
-        }
-    }
-    
-    /// json type
-    public var type: Type { get { return _type } }
-    
-    /// Error in JSON
-    public var error: NSError? { get { return self._error } }
-    
-    /// The static null json
-    @available(*, unavailable, renamed="null")
-    public static var nullJSON: JSON { get { return null } }
-    public static var null: JSON { get { return JSON(NSNull()) } }
-}
-
-// MARK: - CollectionType, SequenceType, Indexable
-extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
-    
-    public typealias Generator = JSONGenerator
-    
-    public typealias Index = JSONIndex
-    
-    public var startIndex: JSON.Index {
-        switch self.type {
-        case .Array:
-            return JSONIndex(arrayIndex: self.rawArray.startIndex)
-        case .Dictionary:
-            return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
-        default:
-            return JSONIndex()
-        }
-    }
-    
-    public var endIndex: JSON.Index {
-        switch self.type {
-        case .Array:
-            return JSONIndex(arrayIndex: self.rawArray.endIndex)
-        case .Dictionary:
-            return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
-        default:
-            return JSONIndex()
-        }
-    }
-    
-    public subscript (position: JSON.Index) -> JSON.Generator.Element {
-        switch self.type {
-        case .Array:
-            return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
-        case .Dictionary:
-            let (key, value) = self.rawDictionary[position.dictionaryIndex!]
-            return (key, JSON(value))
-        default:
-            return ("", JSON.null)
-        }
-    }
-    
-    /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
-    public var isEmpty: Bool {
-        get {
-            switch self.type {
-            case .Array:
-                return self.rawArray.isEmpty
-            case .Dictionary:
-                return self.rawDictionary.isEmpty
-            default:
-                return true
-            }
-        }
-    }
-    
-    /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
-    public var count: Int {
-        switch self.type {
-        case .Array:
-            return self.rawArray.count
-        case .Dictionary:
-            return self.rawDictionary.count
-        default:
-            return 0
-        }
-    }
-    
-    public func underestimateCount() -> Int {
-        switch self.type {
-        case .Array:
-            return self.rawArray.underestimateCount()
-        case .Dictionary:
-            return self.rawDictionary.underestimateCount()
-        default:
-            return 0
-        }
-    }
-    
-    /**
-    If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
-    
-    - returns: Return a *generator* over the elements of JSON.
-    */
-    public func generate() -> JSON.Generator {
-        return JSON.Generator(self)
-    }
-}
-
-public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
-    
-    let arrayIndex: Int?
-    let dictionaryIndex: DictionaryIndex<String, AnyObject>?
-    
-    let type: Type
-    
-    init(){
-        self.arrayIndex = nil
-        self.dictionaryIndex = nil
-        self.type = .Unknown
-    }
-    
-    init(arrayIndex: Int) {
-        self.arrayIndex = arrayIndex
-        self.dictionaryIndex = nil
-        self.type = .Array
-    }
-    
-    init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
-        self.arrayIndex = nil
-        self.dictionaryIndex = dictionaryIndex
-        self.type = .Dictionary
-    }
-    
-    public func successor() -> JSONIndex {
-        switch self.type {
-        case .Array:
-            return JSONIndex(arrayIndex: self.arrayIndex!.successor())
-        case .Dictionary:
-            return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
-        default:
-            return JSONIndex()
-        }
-    }
-}
-
-public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
-    switch (lhs.type, rhs.type) {
-    case (.Array, .Array):
-        return lhs.arrayIndex == rhs.arrayIndex
-    case (.Dictionary, .Dictionary):
-        return lhs.dictionaryIndex == rhs.dictionaryIndex
-    default:
-        return false
-    }
-}
-
-public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
-    switch (lhs.type, rhs.type) {
-    case (.Array, .Array):
-        return lhs.arrayIndex < rhs.arrayIndex
-    case (.Dictionary, .Dictionary):
-        return lhs.dictionaryIndex < rhs.dictionaryIndex
-    default:
-        return false
-    }
-}
-
-public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
-    switch (lhs.type, rhs.type) {
-    case (.Array, .Array):
-        return lhs.arrayIndex <= rhs.arrayIndex
-    case (.Dictionary, .Dictionary):
-        return lhs.dictionaryIndex <= rhs.dictionaryIndex
-    default:
-        return false
-    }
-}
-
-public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
-    switch (lhs.type, rhs.type) {
-    case (.Array, .Array):
-        return lhs.arrayIndex >= rhs.arrayIndex
-    case (.Dictionary, .Dictionary):
-        return lhs.dictionaryIndex >= rhs.dictionaryIndex
-    default:
-        return false
-    }
-}
-
-public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
-    switch (lhs.type, rhs.type) {
-    case (.Array, .Array):
-        return lhs.arrayIndex > rhs.arrayIndex
-    case (.Dictionary, .Dictionary):
-        return lhs.dictionaryIndex > rhs.dictionaryIndex
-    default:
-        return false
-    }
-}
-
-public struct JSONGenerator : GeneratorType {
-    
-    public typealias Element = (String, JSON)
-    
-    private let type: Type
-    private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
-    private var arrayGenerate: IndexingGenerator<[AnyObject]>?
-    private var arrayIndex: Int = 0
-    
-    init(_ json: JSON) {
-        self.type = json.type
-        if type == .Array {
-            self.arrayGenerate = json.rawArray.generate()
-        }else {
-            self.dictionayGenerate = json.rawDictionary.generate()
-        }
-    }
-    
-    public mutating func next() -> JSONGenerator.Element? {
-        switch self.type {
-        case .Array:
-            if let o = self.arrayGenerate!.next() {
-                return (String(self.arrayIndex++), JSON(o))
-            } else {
-                return nil
-            }
-        case .Dictionary:
-            if let (k, v): (String, AnyObject) = self.dictionayGenerate!.next() {
-                return (k, JSON(v))
-            } else {
-                return nil
-            }
-        default:
-            return nil
-        }
-    }
-}
-
-// MARK: - Subscript
-
-/**
-*  To mark both String and Int can be used in subscript.
-*/
-public protocol JSONSubscriptType {}
-
-extension Int: JSONSubscriptType {}
-
-extension String: JSONSubscriptType {}
-
-extension JSON {
-    
-    /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
-    private subscript(index index: Int) -> JSON {
-        get {
-            if self.type != .Array {
-                var r = JSON.null
-                r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
-                return r
-            } else if index >= 0 && index < self.rawArray.count {
-                return JSON(self.rawArray[index])
-            } else {
-                var r = JSON.null
-                r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
-                return r
-            }
-        }
-        set {
-            if self.type == .Array {
-                if self.rawArray.count > index && newValue.error == nil {
-                    self.rawArray[index] = newValue.object
-                }
-            }
-        }
-    }
-    
-    /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
-    private subscript(key key: String) -> JSON {
-        get {
-            var r = JSON.null
-            if self.type == .Dictionary {
-                if let o = self.rawDictionary[key] {
-                    r = JSON(o)
-                } else {
-                    r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
-                }
-            } else {
-                r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
-            }
-            return r
-        }
-        set {
-            if self.type == .Dictionary && newValue.error == nil {
-                self.rawDictionary[key] = newValue.object
-            }
-        }
-    }
-    
-    /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`,  return `subscript(key:)`.
-    private subscript(sub sub: JSONSubscriptType) -> JSON {
-        get {
-            if sub is String {
-                return self[key:sub as! String]
-            } else {
-                return self[index:sub as! Int]
-            }
-        }
-        set {
-            if sub is String {
-                self[key:sub as! String] = newValue
-            } else {
-                self[index:sub as! Int] = newValue
-            }
-        }
-    }
-    
-    /**
-    Find a json in the complex data structuresby using the Int/String's array.
-    
-    - parameter path: The target json's path. Example:
-    
-    let json = JSON[data]
-    let path = [9,"list","person","name"]
-    let name = json[path]
-    
-    The same as: let name = json[9]["list"]["person"]["name"]
-    
-    - returns: Return a json found by the path or a null json with error
-    */
-    public subscript(path: [JSONSubscriptType]) -> JSON {
-        get {
-            return path.reduce(self) { $0[sub: $1] }
-        }
-        set {
-            switch path.count {
-            case 0:
-                return
-            case 1:
-                self[sub:path[0]].object = newValue.object
-            default:
-                var aPath = path; aPath.removeAtIndex(0)
-                var nextJSON = self[sub: path[0]]
-                nextJSON[aPath] = newValue
-                self[sub: path[0]] = nextJSON
-            }
-        }
-    }
-    
-    /**
-    Find a json in the complex data structuresby using the Int/String's array.
-    
-    - parameter path: The target json's path. Example:
-    
-    let name = json[9,"list","person","name"]
-    
-    The same as: let name = json[9]["list"]["person"]["name"]
-    
-    - returns: Return a json found by the path or a null json with error
-    */
-    public subscript(path: JSONSubscriptType...) -> JSON {
-        get {
-            return self[path]
-        }
-        set {
-            self[path] = newValue
-        }
-    }
-}
-
-// MARK: - LiteralConvertible
-
-extension JSON: Swift.StringLiteralConvertible {
-    
-    public init(stringLiteral value: StringLiteralType) {
-        self.init(value)
-    }
-    
-    public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
-        self.init(value)
-    }
-    
-    public init(unicodeScalarLiteral value: StringLiteralType) {
-        self.init(value)
-    }
-}
-
-extension JSON: Swift.IntegerLiteralConvertible {
-    
-    public init(integerLiteral value: IntegerLiteralType) {
-        self.init(value)
-    }
-}
-
-extension JSON: Swift.BooleanLiteralConvertible {
-    
-    public init(booleanLiteral value: BooleanLiteralType) {
-        self.init(value)
-    }
-}
-
-extension JSON: Swift.FloatLiteralConvertible {
-    
-    public init(floatLiteral value: FloatLiteralType) {
-        self.init(value)
-    }
-}
-
-extension JSON: Swift.DictionaryLiteralConvertible {
-    
-    public init(dictionaryLiteral elements: (String, AnyObject)...) {
-        self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
-            var d = dictionary
-            d[element.0] = element.1
-            return d
-            })
-    }
-}
-
-extension JSON: Swift.ArrayLiteralConvertible {
-    
-    public init(arrayLiteral elements: AnyObject...) {
-        self.init(elements)
-    }
-}
-
-extension JSON: Swift.NilLiteralConvertible {
-    
-    public init(nilLiteral: ()) {
-        self.init(NSNull())
-    }
-}
-
-// MARK: - Raw
-
-extension JSON: Swift.RawRepresentable {
-    
-    public init?(rawValue: AnyObject) {
-        if JSON(rawValue).type == .Unknown {
-            return nil
-        } else {
-            self.init(rawValue)
-        }
-    }
-    
-    public var rawValue: AnyObject {
-        return self.object
-    }
-    
-    public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
-        guard NSJSONSerialization.isValidJSONObject(self.object) else {
-            throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
-        }
-        
-        return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
-    }
-    
-    public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
-        switch self.type {
-        case .Array, .Dictionary:
-            do {
-                let data = try self.rawData(options: opt)
-                return NSString(data: data, encoding: encoding) as? String
-            } catch _ {
-                return nil
-            }
-        case .String:
-            return self.rawString
-        case .Number:
-            return self.rawNumber.stringValue
-        case .Bool:
-            return self.rawNumber.boolValue.description
-        case .Null:
-            return "null"
-        default:
-            return nil
-        }
-    }
-}
-
-// MARK: - Printable, DebugPrintable
-
-extension JSON: Swift.Printable, Swift.DebugPrintable {
-    
-    public var description: String {
-        if let string = self.rawString(options:.PrettyPrinted) {
-            return string
-        } else {
-            return "unknown"
-        }
-    }
-    
-    public var debugDescription: String {
-        return description
-    }
-}
-
-// MARK: - Array
-
-extension JSON {
-    
-    //Optional [JSON]
-    public var array: [JSON]? {
-        get {
-            if self.type == .Array {
-                return self.rawArray.map{ JSON($0) }
-            } else {
-                return nil
-            }
-        }
-    }
-    
-    //Non-optional [JSON]
-    public var arrayValue: [JSON] {
-        get {
-            return self.array ?? []
-        }
-    }
-    
-    //Optional [AnyObject]
-    public var arrayObject: [AnyObject]? {
-        get {
-            switch self.type {
-            case .Array:
-                return self.rawArray
-            default:
-                return nil
-            }
-        }
-        set {
-            if let array = newValue {
-                self.object = array
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-}
-
-// MARK: - Dictionary
-
-extension JSON {
-    
-    //Optional [String : JSON]
-    public var dictionary: [String : JSON]? {
-        if self.type == .Dictionary {
-            return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
-                var d = dictionary
-                d[element.0] = JSON(element.1)
-                return d
-            }
-        } else {
-            return nil
-        }
-    }
-    
-    //Non-optional [String : JSON]
-    public var dictionaryValue: [String : JSON] {
-        return self.dictionary ?? [:]
-    }
-    
-    //Optional [String : AnyObject]
-    public var dictionaryObject: [String : AnyObject]? {
-        get {
-            switch self.type {
-            case .Dictionary:
-                return self.rawDictionary
-            default:
-                return nil
-            }
-        }
-        set {
-            if let v = newValue {
-                self.object = v
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-}
-
-// MARK: - Bool
-
-extension JSON: Swift.BooleanType {
-    
-    //Optional bool
-    public var bool: Bool? {
-        get {
-            switch self.type {
-            case .Bool:
-                return self.rawNumber.boolValue
-            default:
-                return nil
-            }
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(bool: newValue!)
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-    
-    //Non-optional bool
-    public var boolValue: Bool {
-        get {
-            switch self.type {
-            case .Bool, .Number, .String:
-                return self.object.boolValue
-            default:
-                return false
-            }
-        }
-        set {
-            self.object = NSNumber(bool: newValue)
-        }
-    }
-}
-
-// MARK: - String
-
-extension JSON {
-    
-    //Optional string
-    public var string: String? {
-        get {
-            switch self.type {
-            case .String:
-                return self.object as? String
-            default:
-                return nil
-            }
-        }
-        set {
-            if newValue != nil {
-                self.object = NSString(string:newValue!)
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-    
-    //Non-optional string
-    public var stringValue: String {
-        get {
-            switch self.type {
-            case .String:
-                return self.object as! String
-            case .Number:
-                return self.object.stringValue
-            case .Bool:
-                return (self.object as! Bool).description
-            default:
-                return ""
-            }
-        }
-        set {
-            self.object = NSString(string:newValue)
-        }
-    }
-}
-
-// MARK: - Number
-extension JSON {
-    
-    //Optional number
-    public var number: NSNumber? {
-        get {
-            switch self.type {
-            case .Number, .Bool:
-                return self.rawNumber
-            default:
-                return nil
-            }
-        }
-        set {
-            self.object = newValue ?? NSNull()
-        }
-    }
-    
-    //Non-optional number
-    public var numberValue: NSNumber {
-        get {
-            switch self.type {
-            case .String:
-                let decimal = NSDecimalNumber(string: self.object as? String)
-                if decimal == NSDecimalNumber.notANumber() {  // indicates parse error
-                    return NSDecimalNumber.zero()
-                }
-                return decimal
-            case .Number, .Bool:
-                return self.object as! NSNumber
-            default:
-                return NSNumber(double: 0.0)
-            }
-        }
-        set {
-            self.object = newValue
-        }
-    }
-}
-
-//MARK: - Null
-extension JSON {
-    
-    public var null: NSNull? {
-        get {
-            switch self.type {
-            case .Null:
-                return self.rawNull
-            default:
-                return nil
-            }
-        }
-        set {
-            self.object = NSNull()
-        }
-    }
-    public func isExists() -> Bool{
-        if let errorValue = error where errorValue.code == ErrorNotExist{
-            return false
-        }
-        return true
-    }
-}
-
-//MARK: - URL
-extension JSON {
-    
-    //Optional URL
-    public var URL: NSURL? {
-        get {
-            switch self.type {
-            case .String:
-                if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
-                    return NSURL(string: encodedString_)
-                } else {
-                    return nil
-                }
-            default:
-                return nil
-            }
-        }
-        set {
-            self.object = newValue?.absoluteString ?? NSNull()
-        }
-    }
-}
-
-// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
-
-extension JSON {
-    
-    public var double: Double? {
-        get {
-            return self.number?.doubleValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(double: newValue!)
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-    
-    public var doubleValue: Double {
-        get {
-            return self.numberValue.doubleValue
-        }
-        set {
-            self.object = NSNumber(double: newValue)
-        }
-    }
-    
-    public var float: Float? {
-        get {
-            return self.number?.floatValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(float: newValue!)
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-    
-    public var floatValue: Float {
-        get {
-            return self.numberValue.floatValue
-        }
-        set {
-            self.object = NSNumber(float: newValue)
-        }
-    }
-    
-    public var int: Int? {
-        get {
-            return self.number?.longValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(integer: newValue!)
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-    
-    public var intValue: Int {
-        get {
-            return self.numberValue.integerValue
-        }
-        set {
-            self.object = NSNumber(integer: newValue)
-        }
-    }
-    
-    public var uInt: UInt? {
-        get {
-            return self.number?.unsignedLongValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(unsignedLong: newValue!)
-            } else {
-                self.object = NSNull()
-            }
-        }
-    }
-    
-    public var uIntValue: UInt {
-        get {
-            return self.numberValue.unsignedLongValue
-        }
-        set {
-            self.object = NSNumber(unsignedLong: newValue)
-        }
-    }
-    
-    public var int8: Int8? {
-        get {
-            return self.number?.charValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(char: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var int8Value: Int8 {
-        get {
-            return self.numberValue.charValue
-        }
-        set {
-            self.object = NSNumber(char: newValue)
-        }
-    }
-    
-    public var uInt8: UInt8? {
-        get {
-            return self.number?.unsignedCharValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(unsignedChar: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var uInt8Value: UInt8 {
-        get {
-            return self.numberValue.unsignedCharValue
-        }
-        set {
-            self.object = NSNumber(unsignedChar: newValue)
-        }
-    }
-    
-    public var int16: Int16? {
-        get {
-            return self.number?.shortValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(short: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var int16Value: Int16 {
-        get {
-            return self.numberValue.shortValue
-        }
-        set {
-            self.object = NSNumber(short: newValue)
-        }
-    }
-    
-    public var uInt16: UInt16? {
-        get {
-            return self.number?.unsignedShortValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(unsignedShort: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var uInt16Value: UInt16 {
-        get {
-            return self.numberValue.unsignedShortValue
-        }
-        set {
-            self.object = NSNumber(unsignedShort: newValue)
-        }
-    }
-    
-    public var int32: Int32? {
-        get {
-            return self.number?.intValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(int: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var int32Value: Int32 {
-        get {
-            return self.numberValue.intValue
-        }
-        set {
-            self.object = NSNumber(int: newValue)
-        }
-    }
-    
-    public var uInt32: UInt32? {
-        get {
-            return self.number?.unsignedIntValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(unsignedInt: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var uInt32Value: UInt32 {
-        get {
-            return self.numberValue.unsignedIntValue
-        }
-        set {
-            self.object = NSNumber(unsignedInt: newValue)
-        }
-    }
-    
-    public var int64: Int64? {
-        get {
-            return self.number?.longLongValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(longLong: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var int64Value: Int64 {
-        get {
-            return self.numberValue.longLongValue
-        }
-        set {
-            self.object = NSNumber(longLong: newValue)
-        }
-    }
-    
-    public var uInt64: UInt64? {
-        get {
-            return self.number?.unsignedLongLongValue
-        }
-        set {
-            if newValue != nil {
-                self.object = NSNumber(unsignedLongLong: newValue!)
-            } else {
-                self.object =  NSNull()
-            }
-        }
-    }
-    
-    public var uInt64Value: UInt64 {
-        get {
-            return self.numberValue.unsignedLongLongValue
-        }
-        set {
-            self.object = NSNumber(unsignedLongLong: newValue)
-        }
-    }
-}
-
-//MARK: - Comparable
-extension JSON : Swift.Comparable {}
-
-public func ==(lhs: JSON, rhs: JSON) -> Bool {
-    
-    switch (lhs.type, rhs.type) {
-    case (.Number, .Number):
-        return lhs.rawNumber == rhs.rawNumber
-    case (.String, .String):
-        return lhs.rawString == rhs.rawString
-    case (.Bool, .Bool):
-        return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
-    case (.Array, .Array):
-        return lhs.rawArray as NSArray == rhs.rawArray as NSArray
-    case (.Dictionary, .Dictionary):
-        return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
-    case (.Null, .Null):
-        return true
-    default:
-        return false
-    }
-}
-
-public func <=(lhs: JSON, rhs: JSON) -> Bool {
-    
-    switch (lhs.type, rhs.type) {
-    case (.Number, .Number):
-        return lhs.rawNumber <= rhs.rawNumber
-    case (.String, .String):
-        return lhs.rawString <= rhs.rawString
-    case (.Bool, .Bool):
-        return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
-    case (.Array, .Array):
-        return lhs.rawArray as NSArray == rhs.rawArray as NSArray
-    case (.Dictionary, .Dictionary):
-        return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
-    case (.Null, .Null):
-        return true
-    default:
-        return false
-    }
-}
-
-public func >=(lhs: JSON, rhs: JSON) -> Bool {
-    
-    switch (lhs.type, rhs.type) {
-    case (.Number, .Number):
-        return lhs.rawNumber >= rhs.rawNumber
-    case (.String, .String):
-        return lhs.rawString >= rhs.rawString
-    case (.Bool, .Bool):
-        return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
-    case (.Array, .Array):
-        return lhs.rawArray as NSArray == rhs.rawArray as NSArray
-    case (.Dictionary, .Dictionary):
-        return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
-    case (.Null, .Null):
-        return true
-    default:
-        return false
-    }
-}
-
-public func >(lhs: JSON, rhs: JSON) -> Bool {
-    
-    switch (lhs.type, rhs.type) {
-    case (.Number, .Number):
-        return lhs.rawNumber > rhs.rawNumber
-    case (.String, .String):
-        return lhs.rawString > rhs.rawString
-    default:
-        return false
-    }
-}
-
-public func <(lhs: JSON, rhs: JSON) -> Bool {
-    
-    switch (lhs.type, rhs.type) {
-    case (.Number, .Number):
-        return lhs.rawNumber < rhs.rawNumber
-    case (.String, .String):
-        return lhs.rawString < rhs.rawString
-    default:
-        return false
-    }
-}
-
-private let trueNumber = NSNumber(bool: true)
-private let falseNumber = NSNumber(bool: false)
-private let trueObjCType = String.fromCString(trueNumber.objCType)
-private let falseObjCType = String.fromCString(falseNumber.objCType)
-
-// MARK: - NSNumber: Comparable
-
-extension NSNumber {
-    var isBool:Bool {
-        get {
-            let objCType = String.fromCString(self.objCType)
-            if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
-                || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
-                    return true
-            } else {
-                return false
-            }
-        }
-    }
-}
-
-public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
-    switch (lhs.isBool, rhs.isBool) {
-    case (false, true):
-        return false
-    case (true, false):
-        return false
-    default:
-        return lhs.compare(rhs) == NSComparisonResult.OrderedSame
-    }
-}
-
-public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
-    return !(lhs == rhs)
-}
-
-public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
-    
-    switch (lhs.isBool, rhs.isBool) {
-    case (false, true):
-        return false
-    case (true, false):
-        return false
-    default:
-        return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
-    }
-}
-
-public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
-    
-    switch (lhs.isBool, rhs.isBool) {
-    case (false, true):
-        return false
-    case (true, false):
-        return false
-    default:
-        return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
-    }
-}
-
-public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
-    
-    switch (lhs.isBool, rhs.isBool) {
-    case (false, true):
-        return false
-    case (true, false):
-        return false
-    default:
-        return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
-    }
-}
-
-public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
-    
-    switch (lhs.isBool, rhs.isBool) {
-    case (false, true):
-        return false
-    case (true, false):
-        return false
-    default:
-        return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
-    }
-}

+ 1 - 11
SwifterSampleOSX/main.swift

@@ -5,25 +5,15 @@
 //
 
 import Foundation
-import Swifter
 
 do {
     let server: HttpServer = demoServer(try File.currentWorkingDirectory())
-    server["/SwiftyJSON"] = { request in
-        let js: JSON = ["return": "OK", "isItAJSON": true, "code" : 200]
-        return .OK(.Custom(js, { object in
-            guard let obj = object as? JSON, let rawString = obj.rawString() else {
-                throw SerializationError.InvalidObject
-            }
-            return rawString
-        }))
-    }
     server["/testAfterBaseRoute"] = { request in
         return .OK(.Html("ok !"))
     }
     try server.start(9080)
     print("Server has started ( port = 9080 ). Try to connect now...")
-    NSRunLoop.mainRunLoop().run()
+    NSRunLoop.main().run()
 } catch {
     print("Server start error: \(error)")
 }

+ 1 - 1
SwifterTestsCommon/SwifterTestsHttpParser.swift

@@ -16,7 +16,7 @@ class SwifterTestsHttpParser: XCTestCase {
         
         init(_ content: String) {
             super.init(socketFileDescriptor: -1)
-            self.content.appendContentsOf([UInt8](content.utf8))
+            self.content.append(contentsOf: [UInt8](content.utf8))
         }
 
         override func read() throws -> UInt8 {

+ 1 - 1
SwifterTestsCommon/SwifterTestsWebSocketSession.swift

@@ -16,7 +16,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         
         init(_ content: [UInt8]) {
             super.init(socketFileDescriptor: -1)
-            self.content.appendContentsOf(content)
+            self.content.append(contentsOf: content)
         }
         
         override func read() throws -> UInt8 {