How to generate and use Swift object method signature list? - swift

I realized that I could generate a list of methods:
class A {
let methodList: [A -> Int -> Bool] = [methodA, methodB]
func methodA(val: Int) -> Bool { return true }
func methodB(val: Int) -> Bool { return false }
}
That's great. How do I create a loop that can call these methods? The obvious, like obj.methodList[0](1) doesn't work.

You could do this:
let a = A()
let result = a.methodList[0](a)(1)
since your method probably needs an instance to resolve properly.

Related

Custom swift class properties passed by reference?

I have a custom class that I've written an equal/not equal function test for. I'm trying to test if an object I've modified is equal to the original object, but whenever I modify the second object, the original object seems to be modified as well. Here's some sample code (you can run this in a Playground):
// Custom class
class MyClass {
var foo: Bool = false
static func ==(a: MyClass, b: MyClass) -> Bool {
return (a.foo == b.foo)
}
static func !=(a: MyClass, b: MyClass) -> Bool {
return !(a==b)
}
required init() {
// do nothing
}
}
let originalObj: MyClass = MyClass()
var tempObj: MyClass = MyClass()
tempObj = originalObj
tempObj.foo = true
print(originalObj.foo) // Output: "true" (?!?!)
print(tempObj == originalObj) // Output: "true" (?!?!)
Why does changing the value of tempObj change the value of originalObj, and how can I prevent this behavior?
Classes in swift are Reference Types whereas Structs are Value Types. There are two ways to achieve what you want. You can either use struct instead of class or write a copy method for this class and use that method. Something like this
class MyClass {
var foo: Bool = false
static func ==(a: MyClass, b: MyClass) -> Bool {
return (a.foo == b.foo)
}
static func !=(a: MyClass, b: MyClass) -> Bool {
return !(a==b)
}
required init() {
// do nothing
}
func copy() -> MyClass {
let temp = MyClass()
temp.foo = foo
return temp
}
}
let originalObj: MyClass = MyClass()
var tempObj: MyClass = originalObj.copy()

How to use an Swift object method as a closure?

I'd like to use an object method as a closure because I need to reuse the same closure multiple times in different places in an object. Let's say I have the following:
class A {
func launch(code: Int) -> Bool { return false }
}
And I need a closure that is of type Int -> Bool in the same object. How would I be able to use the launch method as the closure? I'd rather not do something like { self.launch($0) } if I can just directly reference the method.
Instance methods are curried functions which take the instance
as the first argument. Therefore
class A {
func launch(code: Int) -> Bool { return false }
func foo() {
let cl = A.launch(self)
// Alternatively:
let cl = self.dynamicType.launch(self)
// ...
}
}
gives you a closure of the type Int -> Bool.

Can I specify that a class instance can be converted to some type?

Say I have a generic class
class Foo<T> { … }
Can I somehow specify that instances of this class can be converted to T in assignments? Example:
let foo = Foo<Int>()
func useAnInt(a: Int) {}
let getTheInt: Int = foo
useAnInt(foo)
Why not just use the underlying type? (Similar to #MrBeardsley's answer)
class Foo<T> {
var t : T
init(t: T) {
self.t = t
}
}
let foo = Foo(t: 3)
func useAnInt(a: Int) {}
let getTheInt: Int = foo.t
useAnInt(foo.t)
You are not able to do what you are asking. Even though Foo defines a generic type T, instances of Foo are still Foo and cannot be converted to the generic type. The reason you would declare a generic type at the class level is to use it multiple places throughout the class.
class Foo<T> {
var value: T
init(withValue: T) {
self.value = withValue
}
func getSomeValue() -> T {
return self.value
}
}
Generics don't mean the class itself is generic and can be converted.
One way of achieving what you want is to use a dedicated protocol for each of the target types that your class shall be convertible to. Here is very basic example:
protocol BoolAdaptable {
func adaptToBool() -> Bool
}
protocol IntAdaptable {
func adaptToInt() -> Int
}
protocol FloatAdaptable {
func adaptToFloat() -> Float
}
class Foo: BoolAdaptable, IntAdaptable, FloatAdaptable {
var v: NSNumber
init(_ v: NSNumber) {
self.v = v
}
func adaptToBool() -> Bool {
return v.boolValue
}
func adaptToInt() -> Int {
return v.integerValue
}
func adaptToFloat() -> Float {
return v.floatValue
}
}
let foo = Foo(NSNumber(double: 1.23))
let getTheBool = foo.adaptToBool() // true
let getTheInt = foo.adaptToInt() // 1
let getTheFloat = foo.adaptToFloat() // 1.23
This could easily be extended to support more complex conversions.

Write a custom access operator in Swift

I implemented a helper to have an array of unowned references:
class Unowned<T: AnyObject>
{
unowned var value : T
init (value: T) { self.value = value }
func get() -> T { return self.value }
}
Now, it is possible to do [ Unowned<Foo> ]. However, I'm not satisfied with having the additional get() method to retrieve the underlying object. So, I wanted to write a custom binary operator, e.g. --> for being able to do
for unownedFoo in ArrayOfUnownedFoos
{
var bar : Int = unownedFoo-->method()
}
My current approach is to define
infix operator --> { }
func --><T> (inout lhs: Unowned<T>, inout rhs: () -> Int) -> Int
{
}
The idea I had behind this is:
lhs is obvisouly the object I get out of the array, on which I want to perform the call on
rhs is the method I desire to call. In this case method() would not take no parameters and return an Int, and therefore
The return value is int.
However, the following problems / uncertainties arise:
Is this the correct approach?
Are my assumptions above correct?
How can I call the provided closure rhs on the instance of the extracted Unowned<T>, e.g. (pseudocode) lhs.value.rhs(). If method() was static, I could do T.method(lhs.value), but then I would have to extract the name of the method somehow to make it more generic.
Maybe, a postfix operator is rather simple.
postfix operator * {}
postfix func *<T>(v:Unowned<T>) -> T {
return v.value
}
// Usage:
for unownedFoo in ArrayOfUnownedFoos {
var bar : Int = unownedFoo*.method()
}
Use something like:
func --> <T:AnyObject, V> (lhs: Unowned<T>, rhs: (T) -> V) -> V
{
return rhs (lhs.get())
}
and then use it as:
for unownedFoo in ArrayOfUnownedFoos
{
var bar : Int = unownedFoo-->{ (val:Int) in return 2*val }
}
Specifically, you don't want to use method() as that itself is a function call - which you probably don't want unless method() is actually returning a closure.

Array of functions in Swift

How can I store an array of functions to callback later in an array like in JavaScript? Any and AnyObject type cannot hold functions with different types of method signatures.
You can use an enum to put various functions into the Array and then extract the functions with a switch.
enum MyFuncs {
case Arity0 ( Void -> Void )
case Arity2 ( (Int, String) -> Void)
}
func someFunc(n:Int, S:String) { }
func boringFunc() {}
var funcs = Array<MyFuncs>()
funcs.append(MyFuncs.Arity0(boringFunc))
funcs.append( MyFuncs.Arity2(someFunc))
for f in funcs {
switch f {
case let .Arity0(f):
f() // call the function with no arguments
case let .Arity2(f):
f(2,"fred") // call the function with two args
}
}
Note: this answer is for Swift versions 1.0 and lower.
Functions that have different parameters and return types are of a different type so they can't be stored in an array together. They also don't conform to the Any or AnyObject protocols.
If you have functions with the same parameters though you can work around that. Even though the functions below return a tuple of Double and an Int, they can both be defined as () -> Any function types.
func func1 () -> Int {
return 1
}
func func2 () -> (Double, Double){
return (2, 3)
}
var a: () -> Int = func1
var b: () -> (Double, Double) = func2
var arr: Array< () -> Any> = [a, b]
Below is an example with both an array and a dictionary. Tested and working in Xcode 6.1 (6A1046a). Note that functions from dictionaries must first be unwrapped.
This technique does however fall apart when the functions have different parameter or return types, for the reasons explained by connor in his answer.
class MyViewController: UIViewController
{
let arrayOfFunctions = [function1, function2]
let dictionaryOfFunctions = [
"function1": function1,
"function2": function2
]
func function1() {
NSLog("function1")
}
func function2() {
NSLog("function2")
}
override func viewDidLoad()
{
let fn1 = arrayOfFunctions[0]
fn1(self)()
let fn2 = dictionaryOfFunctions["function2"]
fn2!(self)()
}
}
As of Swift 1.1, all function types conform to Any, so you can hold functions in an Any array.
func foo (str: String) -> Int {
return 1
}
func bar () -> (Double, Double){
return (2, 3)
}
var a: Any = foo
var b: Any = bar
var arr: Any = [a, b]
A simpler approach to call stored function in array on demand , to use parameters a simple workaround is to make dict args and use it inside the function.
var args = [ "a" : 1, "b" : 2 ]
var requestQueue : [() -> Void] = []
func a() -> Void {
let param = args["a"]
print(param!)
}
func b() -> Void {
let param = args["b"]
print(param!)
}
requestQueue.append(a)
requestQueue.append(b)
for item in requestQueue {
item() //calling the functions
}