Skip to content

Commit

Permalink
change AnyObject to Any and adding warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
evermeer committed Oct 26, 2016
1 parent 066e05f commit d3e5f4a
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 25 deletions.
3 changes: 2 additions & 1 deletion EVReflection.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Pod::Spec.new do |s|
#

s.name = "EVReflection"
s.version = "3.1.2"
s.version = "3.1.3"
s.summary = "iOS: Swift helper library with reflection functions"
s.description = "Swift helper library with reflection functions including support for NSCoding, Printable, Hashable, Equatable and JSON"
s.homepage = "https://github.com/evermeer/EVReflection"
Expand All @@ -35,6 +35,7 @@ s.license = { :type => "MIT", :file => "LICENSE" }
#

s.author = "evermeer"
s.authors = { 'Edwin Vermeer' => '[email protected]' }
s.social_media_url = "http://twitter.com/evermeer"

# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
Expand Down
6 changes: 5 additions & 1 deletion EVReflection/EVReflectionTests/EVReflectionJsonTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,29 @@ class EVReflectionJsonTests: XCTestCase {
print("json = \(json2)")
}

func testJsonUser() {
func testInvalidJsonOrObject() {
let json: String = "{\"id\": 24, \"close_friends\": {}}"
let user = User(json: json)
XCTAssertTrue(user.id == 24, "id should have been set to 24")
XCTAssertTrue(user.closeFriends?.count == 1, "friends should have 1 (empty) user")

NSLog("\n\n===>This will generate an error because you can't create a dictionary for invalid json")
let a = EVReflection.dictionaryFromJson(nil)
XCTAssertEqual(a.count, 0, "Can't create a dictionairy from nil")

NSLog("\n\n===>This will generate an error because you can't create a dictionary for invalid json")
let b = EVReflection.dictionaryFromJson("[{\"asdf\"}")
XCTAssertEqual(b.count, 0, "Can't create a dictionairy from nonsence")

NSLog("\n\n===>This will generate a warning because you can't create a dictionary for a non NSObject type")
let c = EVReflection.arrayFromJson(type: MyEnumFive.ok, json: "[{\"id\": 24}]")
XCTAssertEqual(c.count, 0, "Can't create a dictionairy for a non NSObject type")

NSLog("\n\n===>This will generate an error because you can't create a dictionary for invalid json")
let d = EVReflection.arrayFromJson(type: User(), json: "[{\"id\": 24}")
XCTAssertEqual(d.count, 0, "Can't create a dictionairy for invalid json")

NSLog("\n\n===>This will generate an error because you can't create a dictionary for invalid json")
let e = EVReflection.arrayFromJson(type: User(), json: "")
XCTAssertEqual(e.count, 0, "Can't create a dictionairy for invalid json")
}
Expand Down
14 changes: 14 additions & 0 deletions EVReflection/EVReflectionTests/EVReflectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -384,9 +384,23 @@ class EVReflectionTests: XCTestCase {
print(arrObj2)
XCTAssertEqual(arrObj2.strings[0], "a")
}

func testIssue33() {
let json = "{\"id\":121,\"active\":false}"
let object = MyObject(json: json)
let newJson = object.toJsonString()
print("back to json = \(newJson)\n\nobject description = \(object)")
}
}


class A81: EVObject {
var openId: String = ""
}


class MyObject : EVObject {

var id : Int = 0
var active: Bool = false
}
6 changes: 3 additions & 3 deletions EVReflection/EVReflectionTests/WorkaroundEnumTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,14 @@ class EVReflectionTests2: XCTestCase {
print("\(test)")
var comments = EVReflection.arrayFromJson(type: Comment(), json: test)
var comments2 = [Comment](json: test)
print(comments[0].testuserinfo?.uid)
print(comments2[0].testuserinfo?.uid)
print(comments[0].testuserinfo?.uid ?? "")
print(comments2[0].testuserinfo?.uid ?? "")
}

func testTemp2() {
let test = "[\n {\n \"status\" : \"0\",\n \"content\" : \"Shuru\",\n \"ctime\" : \"1438250556\",\n \"img\" : \"\",\n \"isvote\" : 0,\n \"testuserinfo\" : {\n \"avatar\" : \"\",\n \"uid\" : \"d8b81b21c72f1177300247e2d8d88ec5\",\n \"telnum\" : \"18565280137\",\n \"is_seller\" : \"0\",\n \"sex\" : \"\",\n \"name\" : \"\",\n \"interest\" : \"\"\n },\n \"commentid\" : \"22\",\n \"fabric\" : null,\n \"sound\" : \"\",\n \"vote\" : \"0\",\n \"seller_card\" : null\n }\n]"
let comments = EVReflection.arrayFromJson(type: Comment(), json: test)
print(comments[0].testuserinfo?.telnum)
print(comments[0].testuserinfo?.telnum ?? "")
}
}

Expand Down
40 changes: 20 additions & 20 deletions EVReflection/pod/EVReflection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ final public class EVReflection {
let useKey: String = (mapping ?? objectKey) as? String ?? ""
let original: Any? = getValue(anyObject, key: useKey)
let dictKey: String = cleanupKey(anyObject, key: objectKey, tryMatch: types) ?? ""
let (dictValue, valid) = dictionaryAndArrayConversion(anyObject, key: objectKey, fieldType: types[dictKey] as? String ?? types[useKey] as? String, original: original, theDictValue: v as AnyObject?, conversionOptions: conversionOptions)
let (dictValue, valid) = dictionaryAndArrayConversion(anyObject, key: objectKey, fieldType: types[dictKey] as? String ?? types[useKey] as? String, original: original, theDictValue: v as Any?, conversionOptions: conversionOptions)
if dictValue != nil {
let value: AnyObject? = valid ? dictValue : (v as AnyObject)
let value: Any? = valid ? dictValue : (v as Any)
if let key: String = keyMapping[k as? String ?? ""] as? String {
setObjectValue(anyObject, key: key, theValue: value, typeInObject: types[key] as? String, valid: valid, conversionOptions: conversionOptions)
} else {
Expand Down Expand Up @@ -177,17 +177,16 @@ final public class EVReflection {
- returns: The dictionary representation of the json
*/
public class func dictionaryFromJson(_ json: String?) -> NSDictionary {
var result = NSDictionary()
let result = NSMutableDictionary()
if json == nil {
return result
}
if let jsonData = json!.data(using: String.Encoding.utf8) {
print("ERROR: nil is not valid json!")
} else if let jsonData = json!.data(using: String.Encoding.utf8) {
do {
if let jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
result = jsonDic
return jsonDic
}
} catch {
print("ERROR: Invalid json!")
print("ERROR: Invalid json! \(error.localizedDescription)")
}
}
return result
Expand All @@ -205,6 +204,7 @@ final public class EVReflection {
public class func arrayFromJson<T>(_ theObject: NSObject? = nil, type: T, json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> [T] {
var result = [T]()
if json == nil {
print("ERROR: nil is not valid json!")
return result
}
let jsonData = json!.data(using: String.Encoding.utf8)!
Expand All @@ -221,7 +221,7 @@ final public class EVReflection {
})
}
} catch {
print("ERROR: Invalid json!")
print("ERROR: Invalid json! \(error.localizedDescription)")
}
return result
}
Expand Down Expand Up @@ -268,12 +268,12 @@ final public class EVReflection {
- returns: The string representation of the object
*/
public class func description(_ theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize) -> String {
let (hasKeys, _) = toDictionary(theObject, conversionOptions: conversionOptions)

let (dict, _) = toDictionary(theObject, conversionOptions: conversionOptions)
var description: String = (swiftStringFromClass(theObject)) + " {\n hash = \(hashValue(theObject))"
description = description + hasKeys.map {" \($0) = \($1)"}.reduce("") {"\($0)\n\($1)"} + "\n}\n"
description = description + dict.map {" \($0) = \($1)"}.reduce("") {"\($0)\n\($1)"} + "\n}\n"
return description
}


/**
Create a hashvalue for the object
Expand Down Expand Up @@ -591,7 +591,7 @@ final public class EVReflection {
} else if let value = theValue as? EVRaw {
theValue = value.anyRawValue
} else if let value = theValue as? EVAssociated {
let (enumValue, enumType, _) = valueForAny(theValue, key: value.associated.label, anyValue: value.associated.value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents)
let (enumValue, enumType, _) = valueForAny(theValue, key: value.associated.label, anyValue: value.associated.value as Any, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents)
valueType = enumType
theValue = enumValue
} else {
Expand Down Expand Up @@ -753,7 +753,7 @@ final public class EVReflection {
- parameter valid: False if a vaue is expected and a dictionary
- parameter conversionOptions: Option set for the various conversion options.
*/
public static func setObjectValue<T>(_ anyObject: T, key: String, theValue: AnyObject?, typeInObject: String? = nil, valid: Bool, conversionOptions: ConversionOptions = .DefaultDeserialize, parents: [NSObject] = []) where T: NSObject {
public static func setObjectValue<T>(_ anyObject: T, key: String, theValue: Any?, typeInObject: String? = nil, valid: Bool, conversionOptions: ConversionOptions = .DefaultDeserialize, parents: [NSObject] = []) where T: NSObject {

guard var value = theValue , (value as? NSNull) == nil else {
return
Expand Down Expand Up @@ -811,7 +811,7 @@ final public class EVReflection {

// Call your own object validators that comply to the format: validate<Key>:Error:
do {
var setValue: AnyObject? = value
var setValue: AnyObject? = value as AnyObject?
try anyObject.validateValue(&setValue, forKey: key)
anyObject.setValue(setValue, forKey: key)
} catch _ {
Expand Down Expand Up @@ -1001,7 +1001,7 @@ final public class EVReflection {

- returns: The converted value plus a boolean indicating if it's an object
*/
fileprivate static func dictionaryAndArrayConversion(_ anyObject: NSObject, key: String, fieldType: String?, original: Any?, theDictValue: AnyObject?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (AnyObject?, Bool) {
fileprivate static func dictionaryAndArrayConversion(_ anyObject: NSObject, key: String, fieldType: String?, original: Any?, theDictValue: Any?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (Any?, Bool) {
var dictValue = theDictValue
var valid = true
if let type = fieldType {
Expand Down Expand Up @@ -1069,10 +1069,10 @@ final public class EVReflection {
*/
fileprivate class func dictToObject<T>(_ type: String, original: T?, dict: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (T?, Bool) where T:NSObject {
if var returnObject = original {
if type != "NSNumber" && type != "NSString" && type != "NSDate" && type.contains("Dictionary<") == false {
if type != "NSNumber" && type != "NSString" && type != "NSDate" && type != "Struct" && type.contains("Dictionary<") == false {
returnObject = setPropertiesfromDictionary(dict, anyObject: returnObject, conversionOptions: conversionOptions)
} else {
if type.contains("Dictionary<") == false {
if type.contains("Dictionary<") == false && type != "Struct" {
(original as? EVObject)?.addStatusMessage(.InvalidClass, message: "Cannot set values on type \(type) from dictionary \(dict)")
print("WARNING: Cannot set values on type \(type) from dictionary \(dict)")
}
Expand Down Expand Up @@ -1204,7 +1204,7 @@ final public class EVReflection {
continue // if propertyGetter is nil, skip getting the property
}

value = propertyGetter()
value = propertyGetter() as Any

let (unboxedValue2, _, _) = valueForAny(theObject, key: originalKey, anyValue: value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents)
unboxedValue = unboxedValue2
Expand Down Expand Up @@ -1297,7 +1297,7 @@ final public class EVReflection {
return convertDictionaryForJsonSerialization(ok, theObject: theObject)
default:
(theObject as? EVObject)?.addStatusMessage(.InvalidType, message: "Unexpected type while converting value for JsonSerialization: \(value)")
NSLog("ERROR: Unexpected type while converting value for JsonSerialization")
NSLog("ERROR: Unexpected type while converting value for JsonSerialization: \(value)")
return "\(value)" as AnyObject
}
}
Expand Down

0 comments on commit d3e5f4a

Please sign in to comment.