Why Memory leaks when initialize array of dictionary in class? - swift

It's my class initializer:
typealias JSONDictionaty = [String: AnyObject]
private var _conditions: [[String: String]]?
init(data: JSONDictionaty) {
if let conditions = data["conditions"] as? [JSONDictionaty] {
if conditions.count > 0 {
self._conditions = [[:]] // init _condition
}
// adding all conditions to _condition variable
for condition in conditions {
if let subCond = condition as? [String: String] ,
type = subCond["type"],
expression = subCond["expression"] {
self._conditions?.append([type: expression])
}
}
}
/// deinit _condition variable
if self._conditions?.count == 0 {
self._conditions = nil
}
}
}
I have leaks on this lines:
if let type = subCond["type"], expression = subCond["expression"] {
self._conditions?.append([type: expression])
}
but if I change above lines to this line, memory leaks will be gone:
self._conditions?.append(subCond)

Related

Swift: checking 2 object from same class have different values?

I'm using swift in my project. I have 2 object from same class(for example object A and object B from Class MyClass):
class MyClass: NSObject {
var someString: String = ""
var someInt: Int = 0
}
...
let A = MyClass()
A.someString = "A object"
A.someInt = 1
let B = MyClass()
B.someString = "B object"
B.someInt = 2
how I can check if same properties have same value, and if not return value and key of the property?
I think we can do this with using Mirror with 2 for loop inside each other, am I write?
I think you're looking for something like this pretty much:
import Foundation
class MyClass {
var someString: String = ""
var someInt: Int = 0
}
let a = MyClass()
a.someString = "A object"
a.someInt = 1
let b = MyClass()
b.someString = "B object"
b.someInt = 2
func compare<T: MyClass>(_ instance: T, with instance2: T) -> [String: AnyHashable] {
let sourceMirror = Mirror(reflecting: instance)
let targetMirror = Mirror(reflecting: instance2)
var output = [String: AnyHashable]()
for sourceChild in sourceMirror.children {
guard let label = sourceChild.label else { continue }
guard let targetChild = (targetMirror.children.first { $0.label! == label }) else {
fatalError("Failed to find target child, since types are same this fatal error should not be fired")
}
guard
let firstValue = sourceChild.value as? AnyHashable,
let secondValue = targetChild.value as? AnyHashable
else {
continue
}
guard firstValue != secondValue else { continue }
output[label] = secondValue
}
return output
}
for result in compare(a, with: b) {
print("label: \(result.key), value: \(result.value)")
}
The downside of this method is all of your fields must be conforming to Hashable protocol if you want to see the difference between these.
The output is:
label: someInt, value: 2
label: someString, value: B object

How do I call a function with parameters?

I am using xcode playgrounds toying around with some code and I get this error Use of unresolved identifier 'colorArray' when I try to call a function. How do I fix this I know it has to be simple.
import Foundation
class Solution{
var colorArray = ["Red","blue","green","black","red","blue","yellow","purple","Red","Red","Red","yellow","yellow","black","green","black","purple","black","yellow","purple","purple","blue","yellow","blue","green","green","yellow","pink"]
func getMostCommonColor(array: [String]) -> [String] {
var topColors: [String] = []
var colorDictionary: [String: Int] = [:]
for color in array {
if let count = colorDictionary[color] {
colorDictionary[color] = count + 1
}else{
colorDictionary[color] = 1
}
}
let highestValue = colorDictionary.values.max()
for (color,count) in colorDictionary {
if colorDictionary[color] == highestValue {
topColors.append(color)
}
}
return topColors
}
}
let solution = Solution()
solution.getMostCommonColor(array: colorArray) //This is where I get the error
The way you've defined it, colorArray is an instance property of Solution, meaning you need to access it through some instance of the Solution class.
You've already created an instance down below, so you could do this:
let solution = Solution()
solution.getMostCommonColor(array: solution.colorArray)
However, I suspect you meant for colorArray to be a global variable of sorts (since this is just a playground, after all), so another option is to move colorArray out of the Solution class:
var colorArray = ["Red","blue","green","black","red","blue","yellow","purple","Red","Red","Red","yellow","yellow","black","green","black","purple","black","yellow","purple","purple","blue","yellow","blue","green","green","yellow","pink"]
class Solution {
func getMostCommonColor(array: [String]) -> [String] {
var topColors: [String] = []
var colorDictionary: [String: Int] = [:]
for color in array {
if let count = colorDictionary[color] {
colorDictionary[color] = count + 1
}else{
colorDictionary[color] = 1
}
}
let highestValue = colorDictionary.values.max()
for (color,count) in colorDictionary {
if colorDictionary[color] == highestValue {
topColors.append(color)
}
}
return topColors
}
}
let solution = Solution()
solution.getMostCommonColor(array: colorArray)

Casting AnyObject to Specific Class

I'm using socket.io Swift Library. With the following line of code,
socket.on("info") { (dataArray, socketAck) -> Void in
let user = dataArray[0] as? User
print(user._id)
}
dataArray[0] is a valid object but user appears to be nil after casting.
Since dataArray[0] returns as an AnyObject,
how can i cast AnyObject to User Object?. Or somehow manage to do what i want with a different approach?
Since after this line
let user = dataArray[0] as? User
you have a nil value inside user it means that you don't have a User value at the first position of dataArray.
Since dataArray comes from a server (as I guess) it probably contains a serialized version of User.
Now we really need to know what really dataArray[0] is. However...
if dataArray[0] contains NSData
In this case try this
let json = JSON(dataArray[0] as! NSData)
let user = User(json:json)
You need to create a constructor that accept AnyObject and read data in it.
I guess in this case dataArray[0] is an JSON Object.
class User {
init(data: [String: AnyObject]) {
username = data["username"] as? String ?? ""
}
}
This is how i manage mine:
// Structure used as parameter
struct InfoStruct {
var nome: String = ""
var sobrenome:String = ""
var nascimentoTimestamp: NSNumber = 0
init() {
}
// Struct to AnyObject
func toAnyObject() -> Any {
var dic = [String:AnyObject?]()
if (nome != "") { dic["nome"] = nome as AnyObject }
if (sobrenome != "") { dic["sobrenome"] = sobrenome as AnyObject }
if (nascimentoTimestamp != 0) { dic["nascimentoTimestamp"] = nascimentoTimestamp as AnyObject }
return dic
}
// AnyObject to Struct
func fromAnyObject(dic:[String:AnyObject]) -> InfoStruct {
var retorno = InfoStruct()
if (dic["nome"] != nil) { retorno.nome = dic["nome"] as? String ?? "" }
if (dic["sobrenome"] != nil) { retorno.sobrenome = dic["sobrenome"] as? String ?? "" }
if (dic["nascimentoTimestamp"] != nil) { retorno.nascimentoTimestamp = dic["nascimentoTimestamp"] as? NSNumber ?? 0 }
return retorno
} }
// User class
class Usuario: NSObject {
var key: String
var admin: Bool
var info: InfoStruct // Struct parameter
init(_ key: String?) {
self.key = key ?? ""
admin = false
info = InfoStruct() // Initializing struct
}
// From Class to AnyObject
func toAnyObject() -> Any {
var dic = [String:AnyObject?]()
if (key != "") { dic["key"] = key as AnyObject }
if (admin != false) { dic["admin"] = admin as AnyObject }
dic["info"] = info.toAnyObject() as AnyObject // Struct
return dic
}
// From AnyObject to Class
func fromAnyObject(dic:[String:AnyObject]) -> Usuario {
let retorno = Usuario(dic["key"] as? String)
if (dic["key"] != nil) { retorno.key = dic["key"] as? String ?? "" }
if (dic["admin"] != nil) { retorno.admin = dic["admin"] as? Bool ?? false }
if (dic["info"] != nil) { retorno.info = InfoStruct.init().fromAnyObject(dic: dic["info"] as! [String : AnyObject]) } // Struct
return retorno
} }
// Using
let dao = FirebaseDAO.init(_type: FirebaseDAOType.firebaseDAOTypeUser)
dao.loadValue(key: uid) { (error, values:[String : AnyObject]) in
if error == nil {
let user = Usuario(values["key"] as? String).fromAnyObject(dic: values)
}
}
I hope it helps!

Get a type of Element of an array in Swift (through reflection)

Let say I have following code
class Foo {
}
var fooArray : Array<Foo> = Array<Foo>()
// This is important because in my code I will get Any (vs Array<Foo)
var fooArrayAny : Any = foo
I want to be able to get a Type Foo out of variable fooArrayAny.
If I had fooArray, I would do something like that:
let type = fooArray.dynamicType.Element().dynamicType
However, this doesn't work with fooArrayAny. It says that it has no member Element()
If you set NSObject as the base class of Foo, then you could use the following code:
class EVReflectionTests: XCTestCase {
func testArrayInstance() {
let fooArray : Array<Foo> = Array<Foo>()
let fooArrayAny : Any = fooArray
if let arr = fooArray as? Array {
let i = arr.getArrayTypeInstance(arr)
print("i = \(i)")
}
}
}
class Foo: NSObject {
}
extension Array {
public func getArrayTypeInstance<T>(arr:Array<T>) -> T {
return arr.getTypeInstance()
}
public func getTypeInstance<T>() -> T {
let nsobjectype : NSObject.Type = T.self as! NSObject.Type
let nsobject: NSObject = nsobjectype.init()
return nsobject as! T
}
}
This code is a snippet of my library EVReflection
Update:
I noticed a mistake in the code above. I used fooArray instead of fooArrayAny. When changing that to fooArrayAny I get the same error as you that the compiler does not have the Element. After playing around with this, I found out a solution that does work. Again it has parts of code of my EVReflection library.
class EVReflectionTests: XCTestCase {
func testArrayInstance() {
let fooArray : Array<Foo> = Array<Foo>()
let fooArrayAny : Any = fooArray
if let _ = fooArrayAny as? NSArray {
var subtype: String = "\(Mirror(reflecting: fooArrayAny))"
subtype = subtype.substringFromIndex((subtype.componentsSeparatedByString("<") [0] + "<").endIndex)
subtype = subtype.substringToIndex(subtype.endIndex.predecessor())
print("The type of the array elements = \(subtype)")
if let instance = swiftClassFromString(subtype) {
print("An instance of the array element = \(instance)")
let type = instance.dynamicType
print("An instance of the array element = \(type)")
}
}
}
// All code below is a copy from the EVReflection library.
func swiftClassFromString(className: String) -> NSObject? {
var result: NSObject? = nil
if className == "NSObject" {
return NSObject()
}
if let anyobjectype : AnyObject.Type = swiftClassTypeFromString(className) {
if let nsobjectype : NSObject.Type = anyobjectype as? NSObject.Type {
let nsobject: NSObject = nsobjectype.init()
result = nsobject
}
}
return result
}
func swiftClassTypeFromString(className: String) -> AnyClass! {
if className.hasPrefix("_Tt") {
return NSClassFromString(className)
}
var classStringName = className
if className.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch) == nil {
let appName = getCleanAppName()
classStringName = "\(appName).\(className)"
}
return NSClassFromString(classStringName)
}
func getCleanAppName(forObject: NSObject? = nil)-> String {
var bundle = NSBundle.mainBundle()
if forObject != nil {
bundle = NSBundle(forClass: forObject!.dynamicType)
}
var appName = bundle.infoDictionary?["CFBundleName"] as? String ?? ""
if appName == "" {
if bundle.bundleIdentifier == nil {
bundle = NSBundle(forClass: EVReflection().dynamicType)
}
appName = (bundle.bundleIdentifier!).characters.split(isSeparator: {$0 == "."}).map({ String($0) }).last ?? ""
}
let cleanAppName = appName
.stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
.stringByReplacingOccurrencesOfString("-", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
return cleanAppName
}
}
class Foo: NSObject {
}
The output of this code will be:
The type of the array elements = Foo
An instance of the array element = <EVReflection_iOS_Tests.Foo: 0x7fd6c20173d0>
An instance of the array element = Foo
Swift 5
Its old but I want to share my version if someone needs it.
I use ModelProtocol and I suggests you use protocol so we can do operation to model via protocol (ex: static instantiating).
protocol ModelProtocol {}
class Foo: ModelProtocol {
}
Since I can't check type is Array, I use CollectionProtocol and create Array extension to get Element via protocol.
protocol CollectionProtocol {
static func getElement() -> Any.Type
}
extension Array: CollectionProtocol {
static func getElement() -> Any.Type {
return Element.self
}
}
Testing.
var fooArray: Array<Foo> = Array<Foo>()
var fooArrayAny: Any = fooArray
let arrayMirrorType = type(of: fooArrayAny)
String(describing: "arrayMirrorType: \(arrayMirrorType)")
if arrayMirrorType is CollectionProtocol.Type {
let collectionType = arrayMirrorType as! CollectionProtocol.Type
String(describing: "collectionType: \(collectionType)")
let elementType = collectionType.getElement()
String(describing: "elementType: \(elementType)")
let modelType = elementType as! ModelProtocol.Type
String(describing: "modelType: \(modelType)")
// ... now you can do operation to modelType via ModelProtocol
}
Printing.
arrayMirrorType: Array<Foo>
collectionType: Array<Foo>
elementType: Foo
modelType: Foo
class Foo {
var foo: Int = 1
}
struct Boo {
var boo: String = "alfa"
}
func f(array: Any) {
let mirror = Mirror(reflecting: array)
let arraytype = mirror.subjectType
switch arraytype {
case is Array<Foo>.Type:
let fooArray = array as! Array<Foo>
print(fooArray)
case is Array<Boo>.Type:
let booArray = array as! Array<Boo>
print(booArray)
default:
print("array is not Array<Foo> nor Array<Boo>")
break
}
}
var fooArray : Array<Foo> = []
fooArray.append(Foo())
var anyArray : Any = fooArray // cast as Any
f(anyArray) // [Foo]
var booArray : Array<Boo> = []
booArray.append(Boo())
anyArray = booArray // cast as Any
f(anyArray) // [Boo(boo: "alfa")]
var intArray : Array<Int> = []
anyArray = intArray // cast as Any
f(anyArray) // array is not Array<Foo> nor Array<Boo>

compute a value to a let struct property in init

I have a swift struct named Product which takes a Dictionary in its init method. I want to compute a price value in a local Price struct within my Product. I want this value to be a let constant since it won't ever change, but swift won't allow me to do that without using var, saying that the let constant is not properly initialized.
How can I make my value property inside my Price struct a let constant in this case?
struct Product {
let price: Price
init(dictionary: Dictionary<String, AnyObject>) {
if let tmp = dictionary["price"] as? Dictionary<String, AnyObject> { price = Price(dictionary: tmp) } else { price = Price() }
}
struct Price {
var value = ""
init() {
}
init(dictionary: Dictionary<String, AnyObject>) {
if let xForY = dictionary["xForY"] as? Array<Int> {
if xForY.count == 2 {
value = "\(xForY[0]) for \(xForY[1])"
}
}
if let xForPrice = dictionary["xForPrice"] as? Array<Int> {
if value == "" && xForPrice.count == 2 {
value = "\(xForPrice[0]) / \(xForPrice[1]):-"
}
}
if let reduced = dictionary["reduced"] as? String {
if value == "" {
value = "\(reduced):-"
}
}
}
}
}
You have to rewrite the code so that the compiler gets what you intend to do actually. It is not clever enough to deduce it from the way you coded it.
I would also suggest that you make the initializer for the Price struct failable instead of using an empty string for the value property. As a consequence of that change the price property of the Product struct becomes an optional.
struct Product {
let price: Price?
init(dictionary: Dictionary<String, AnyObject>) {
if let tmp = dictionary["price"] as? Dictionary<String, AnyObject> {
price = Price(dictionary: tmp)
}
else {
price = nil
}
}
struct Price {
let value : String
init?(dictionary: Dictionary<String, AnyObject>) {
if let xForY = dictionary["xForY"] as? Array<Int> where xForY.count == 2 {
value = "\(xForY[0]) for \(xForY[1])"
}
else if let xForPrice = dictionary["xForPrice"] as? Array<Int> where xForPrice.count == 2 {
value = "\(xForPrice[0]) / \(xForPrice[1]):-"
}
else if let reduced = dictionary["reduced"] as? String {
value = "\(reduced):-"
}
else {
return nil
}
}
}
}
The trouble is that (1) you're assigning to value in the declaration, (2) you're not assigning a value in init(), and (3) you're referencing and reassigning value in init([String: AnyObject]). You can only assign a value to a constant once and can only reference its value after its been assigned to.
To fix the issue, you can either make your property publicly readonly:
private(set) var value: String = ""
Or you can use a second variable inside your init:
struct Price {
let value: String
init() {
self.value = ""
}
init(dictionary: Dictionary<String, AnyObject>) {
var v: String = ""
if let xForY = dictionary["xForY"] as? Array<Int> {
if xForY.count == 2 {
v = "\(xForY[0]) for \(xForY[1])"
}
}
if let xForPrice = dictionary["xForPrice"] as? Array<Int> {
if v == "" && xForPrice.count == 2 {
v = "\(xForPrice[0]) / \(xForPrice[1]):-"
}
}
if let reduced = dictionary["reduced"] as? String {
if v == "" {
v = "\(reduced):-"
}
}
self.value = v
}
}