0001 // 0002 // ExtensionArray.swift 0003 // Gloss 0004 // 0005 // Copyright (c) 2016 Rahul Katariya 0006 // 0007 // Permission is hereby granted, free of charge, to any person obtaining a copy 0008 // of this software and associated documentation files (the "Software"), to deal 0009 // in the Software without restriction, including without limitation the rights 0010 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 0011 // copies of the Software, and to permit persons to whom the Software is 0012 // furnished to do so, subject to the following conditions: 0013 // 0014 // The above copyright notice and this permission notice shall be included in 0015 // all copies or substantial portions of the Software. 0016 // 0017 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 0018 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 0019 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 0020 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 0021 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 0022 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 0023 // THE SOFTWARE. 0024 // 0025 0026 import Foundation 0027 0028 public extension Array where Element: Decodable { 0029 0030 /** 0031 Returns array of new instances created from provided JSON array 0032 0033 Note: The returned array will have only models that successfully 0034 decoded 0035 0036 :parameter: json Array of JSON representations of object 0037 */ 0038 static func fromJSONArray(jsonArray: [JSON]) -> [Element] { 0039 var models: [Element] = [] 0040 0041 for json in jsonArray { 0042 let model = Element(json: json) 0043 0044 if let model = model { 0045 models.append(model) 0046 } 0047 } 0048 0049 return models 0050 } 0051 0052 } 0053 0054 public extension Array where Element: Encodable { 0055 0056 /** 0057 Objects encoded as JSON Array 0058 0059 :returns: JSON array 0060 */ 0061 func toJSONArray() -> [JSON]? { 0062 var jsonArray: [JSON] = [] 0063 0064 for json in self { 0065 if let json = json.toJSON() { 0066 jsonArray.append(json) 0067 } 0068 } 0069 0070 return jsonArray 0071 } 0072 } 0073 0074