Calling function from a class - swift

I am trying to become confident using functions. I am practicing with the code below.
class Arithmetics {
var operand1: Double
var operand2: Double
init(operand1: Double, operand2: Double) {
self.operand1 = operand1
self.operand2 = operand2
}
func AddInsideClass(operand1: Double, operand2: Double) -> Double {
var sum = operand1 + operand2
return sum
}
}
func AddOutsideClass(operand1: Double, operand2: Double) -> Double {
var sum = operand1 + operand2
return sum
}
println(AddOutsideClass(5.5, 4.5))
println(Arithmetics.AddInsideClass(5.5, 4.5))
In the last 2 lines I tried to call the functions and output them on the console. The first println() is calling the function from outside the class, which works fine.
The second println() however gives me an error message that goes like this:
"stdin:23:35: error: extra argument in call
println(Arithmetics.AddInsideClass(5.5, 4.5))
^ ~~~"
What's the problem here?
Is it because I cannot simply call a class method directly? Or can I call class methods only via a class instance like below?
var operation1: Double = Arithmetics.AddInsideClass(5.5, 4.5)

You have two options:
First – using your syntax – you declare the function as static and you can omit the variables and the init function
class Arithmetics {
static func addInsideClass(operand1: Double, operand2: Double) -> Double {
var sum = operand1 + operand2
return sum
}
}
You can call it on the class (the second parameter name is mandatory)
Arithmetics.addInsideClass(5.5, operand2:4.5)
Second you create an instance of the class which now needs no operands in the add function because they are set in the init function.
class Arithmetics {
var operand1: Double
var operand2: Double
init(operand1: Double, operand2: Double) {
self.operand1 = operand1
self.operand2 = operand2
}
func addInsideClass() -> Double {
var sum = operand1 + operand2
return sum
}
}
And the syntax to call it is
let operation1 = Arithmetics(operand1: 5.5, operand2: 4.5)
operation1.addInsideClass()

A class method is a method that operates on class objects rather than
instances of the class.
AddInsideClass is not a class-method. It can only be called using an object of the class Arithmetics and not with the class name itself.
Create an object of the class Arithmetics in order to call its methods in another class.
let arithmeticsClassObj = Arithmetics()
println(arithmeticsClassObj.AddInsideClass(5.5, 4.5))
Reference: Apple Docs

Related

Using overridden math function

Trying to compile this code
pow(10,2)
struct Test {
var i:Int
func pow(_ p:Int) -> Int { return pow(i,p) }
}
var s = Test(i:10)
s.pow(2)
gives me a compiler error. Obviously the standard math.h function pow was blinded out by Swift's scoping rules. This rather smells like a compiler error since the math.h version of pow has a different signature. Is there any way to invoke it, though?
There are two problems: The first is how pow(i,p) is resolved.
As described in Swift 3.0: compiler error when calling global func min<T>(T,T) in Array or Dictionary extension, this
can be solved by prepending the module name to the function call.
The second problem is that there is no pow function taking
two integer arguments. There is
public func powf(_: Float, _: Float) -> Float
public func pow(_: Double, _: Double) -> Double
in the standard math library, and
public func pow(_ x: Decimal, _ y: Int) -> Decimal
in the Foundation library. So you have to choose which one to use,
for example:
struct Test {
var i:Int
func pow(_ p:Int) -> Int {
return lrint(Darwin.pow(Double(i),Double(p)))
}
}
which converts the arguments to Double and rounds the result
back to Int.
Alternatively, use iterated multiplication:
struct Test {
var i: Int
func pow(_ p:Int) -> Int {
return (0..<p).reduce(1) { $0.0 * i }
}
}
I observed at https://codereview.stackexchange.com/a/142850/35991 that
this is faster for small exponents. Your mileage may vary.

Calling a function of an Object that takes a function as its parameter

Say I have the following code:
import Foundation
enum Operation {
case BinaryOperation ((Double, Double) -> Double)
}
var multiply = Operation.BinaryOperation({$0 * $1})
//Error: Cannot call value of non-function type 'Operation'
multiply(3.0,2.0)
How would I call the function multiply here?
Your function is the associated value of an enum value, so you have to extract it first before calling it. One way to do that is to use pattern matching:
if case let .BinaryOperation(function) = multiply {
function(3.0, 2.0)
}
This can also be written as:
if case .BinaryOperation(let function) = multiply {
function(3.0, 2.0)
}

Initializing a variable with a function in a class

I have a class sort of like the one below. It is simplified, but it illustrates my problem. I want to initialize the "number" variable with the function "square".
class SomeClass {
let number: Int
func square (num: Int) -> Int {
return num * num
}
init(num: Int) {
number = square(num)
}
}
But when i make an instance of the class. For example
let instance = SomeClass(num: 2)
it throws the error: use of 'self' in method call 'square' before all stored properties are initialized.
How can i initialize the number by using the function?
In this particular case you can use class method:
class SomeClass {
let number: Int
class func square (num: Int) -> Int {
return num * num
}
init(num: Int) {
number = SomeClass.square(num)
}
}
the only way, how to do what you want to do, is declare the number as var and initialize it with some value
class SomeClass {
var number: Int = 0
func square (num: Int) -> Int {
return num * num
}
init(num: Int) {
number = square(num)
}
}
let instance = SomeClass(num: 2)
instance.number // 4

“Functions are a first-class type” in swift?

the little knowledge , I have about first class function is that it supports passing functions as arguments and we can also return them as the values in another function ... I am very new in Swift programming language can anyone please elaborate it with an example.
A very simple example to demonstrate this behaviour:
func functionA() {
println("Hello by functionA")
}
func executeFunction(function: () -> ()) {
function()
}
executeFunction(functionA)
First-Class functions are functions that can return another functions.
For instance:
func operate( operand: String) -> ((Double, Double) -> Double)?{
func add(a: Double, b: Double) -> Double {
return a + b
}
func min(a: Double, b: Double) -> Double{
return a - b
}
func multi(a: Double, b: Double) -> Double {
return a * b
}
func div (a: Double, b: Double) -> Double{
return a / b
}
switch operand{
case "+":
return add
case "-":
return min
case "*":
return multi
case "/":
return div
default:
return nil
}
}
The function operate returns a function that takes two double as its arguments and returns one double.
The usage of this function is:
var function = operate("+")
print(" 3 + 4 = \(function!(3,4))")
function = operate("-")
print(" 3 - 4 = \(function!(3,4))")
function = operate("*")
print(" 3 * 4 = \(function!(3,4))")
function = operate("/")
print(" 3 / 4 = \(function!(3,4))")
When you don't care about the implementation of a function, using First-Class functions to return these functions become beneficials. Plus, sometimes, you are not responsible to develop (or not authorised ) of the functions like add, min. So someone would develop a First-Class function to you that returns these functions and it is your responsibility to continue ....
A function that returns a function while capturing a value from the lexical environment:
A function of an array of Comparables that returns a function of a test predicate that returns a function of a value that returns a Bool if the value is the extreme of the array under test. (Currying)
Any programming language is said to have first-class-functions, when functions are treated like normal variables. That means a function can be passed as parameter to any other function, can be returned by any function and also can be assigned to any variable.
i.e., (Referring apple's examples)
Passing function as parameter
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
Returning function
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
Properties of First class function
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to
another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, …
refer https://www.geeksforgeeks.org/first-class-functions-python/

Why does the code produces error Type '(int, int)' does not conform to protocol 'IntegerLiteralConvertible'

With the code below, I get "Type '(int, int)' does not conform to protocol 'IntegerLiteralConvertible' instead of missing argument as one would expect. What's IntegerLiteralConvertible and why do you think the compiler produces this error instead for the code below?
I have looked at other SO posts regarding this error but have not gotten any insight from them.
func add(x:Int, y:Int) {
}
add(3)
My best guess is that it tries to convert the (3) tuple into a (Int, Int) tuple.
In fact, this is accepted by the compiler and works as expected:
func add(x: Int, y: Int) -> Int {
return x + y
}
let tuple = (4, 7)
add(tuple)
In playground that outputs 11, which is the expected sum result.
Note: the code above works if the func is global, with no named parameters. If it's an instance or class/static method, then the tuple must include parameter names:
class MyClass {
class func add(# x: Int, y: Int) -> Int {
return x + y
}
}
let tuple = (x: 3, y: 7)
MyClass.add(tuple) // returns 10
As for IntegerLiteralConvertible, it's used to make a class or struct adopting it to be initializable from a literal integer. Let's say you have a struct and you want to be able to instantiate by assigning an literal integer, you achieve it this way:
struct MyDataType : IntegerLiteralConvertible {
var value: Int
static func convertFromIntegerLiteral(value: IntegerLiteralType) -> MyDataType {
return MyDataType(value: value)
}
init(value: Int) {
self.value = value
}
}
and then you can create an instance like this:
let x: MyDataType = 5
It looks like you are trying to use currying — Swift has built-in support for this, but it is not automatic, so you have to be explicit about it when declaring your function:
func add(x:Int)(y:Int) -> Int {
return x + y
}
println(add(3)) // (Function)