How do I call a function with parameters? - swift

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)

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

Why Memory leaks when initialize array of dictionary in class?

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)

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>

extension of Int needs an explicit call to init

I am creating an extension of Int with my own init but I cannot use the init implicitly. Can somebody please explain why? I can however call the init explicitly as shown below.
extension Int {
init?(fromHexString: String) {
let HexRadix:Int = 16
let DigitsString = "0123456789abcdefghijklmnopqrstuvwxyz"
let digits = DigitsString
var result = Int(0)
for digit in fromHexString.lowercaseString {
if let range = digits.rangeOfString(String(digit)) {
let val = Int(distance(digits.startIndex, range.startIndex))
if val >= Int(HexRadix) {
return nil
}
result = result * Int(HexRadix) + val
} else {
return nil
}
}
self = result
}
}
let firstString = "ff"
//This works
let parsedInt:Int = Int.init(fromHexString: firstString)!
println("\(parsedInt)")
//But this does not ; Error: Int is not identical to Int? Why??
let parsedInt1:Int = Int(fromHexString: firstString)!
println("\(parsedInt1)")

Cannot assign to the result of this expression with generics

I have the following generic class where I want to manage a string hash:
class NamedProfile<T> {
private var set = [String:T]()
private var profiles = [String]()
private let userDefaults = NSUserDefaults.standardUserDefaults()
private let profileName:String
var currentSet = ""
init(name:String, set:[String:T]) {
profileName = name
self.set = set
if let existingProfiles = userDefaults.objectForKey(name) as? [String] {
profiles = existingProfiles
}
for key in profiles {
if let existingProfile = userDefaults.objectForKey(profileNamed(name)) as? T {
set[key] = existingProfile // <-- error
}
}
}
private func profileNamed(name:String) -> String { return "\(profileName) \(name)" }
}
Why does the compiler croak in the above assignment?
In
init(name:String, set:[String:T]) {
// ...
set[key] = existingProfile // <-- error
// ...
}
set refers to the (immutable) method parameter.
Use self.set instead to refer to the property.