Passing lists from one function to another in Swift
The numbers: Int...
parameter in sumOf
is called a variadic parameter. That means you can pass in a variable number of that type of parameter, and everything you pass in is converted to an array of that type for you to use within the function.
Because of that, the numbers
parameter inside average
is an array, not a group of parameters like sumOf
is expecting.
You might want to overload sumOf
to accept either one, like this, so your averaging function can call the appropriate version:
func sumOf(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func sumOf(numbers: Int...) -> Int {
return sumOf(numbers)
}
How do I pass value from one function to another?
You have declared them globally in your class so you are able to access them everywhere, as you have done now. No need to create additional variables.
func post() {
let post : [String: Double]=["lat":latPass, "long":longPass]
let dataBaseRef=FIRDatabase.database().reference()
dataBaseRef.child("Location").childByAutoId().setValue(post)
}
Otherwise you could set parameters in your post function:
func post(lat: Double, long: Double) {
let post : [String: Double]=["lat":lat, "long":long]
let dataBaseRef=FIRDatabase.database().reference()
dataBaseRef.child("Location").childByAutoId().setValue(post)
}
To call post now:
post(lat: 11.000, long: 12.000)
Update:
Update your locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
to this:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// if you pass this guard, then you have a valid loction
guard let latitude = manager.location?.coordinate.latitude, let longitude = manager.location?.coordinate.longitude else { return }
let span:MKCoordinateSpan=MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(latitude, longitude)
let region:MKCoordinateRegion=MKCoordinateRegionMake(myLocation, span)
latPass = latitude
longPass = longitude
// Call post here because now you have valid a location
post()
}
Swift pass data from a function to another
You are getting the values from asynchronous functions using budgetDB.observe
.
Then when you call getLeftBudget
you don't have the values in variables yet. You should implement a completion handler function.
This code is not tested, I just used a notepad to adapt as I'm out of office, but the idea is it.
var income = [Double]()
var expenses = [Double]()
var totalIncome: Double = 0
var totalExpenses: Double = 0
typealias returnCalc = (Bool) -> Void
func getIncData(completion: @escaping returnCalc) {
let budgetDB = Database.database().reference().child("Income")
budgetDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let value = snapshotValue["Value"]!
self.income.append(Double(Int(value)!))
self.totalIncome = self.income.reduce(0, +)
self.incomeLabel.text = "Income: " + String(self.totalIncome) + " €";
completion(true)
}
}
func getExpData(completion: @escaping returnCalc) {
let budgetDB = Database.database().reference().child("Expenses")
budgetDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let value = snapshotValue["Value"]!
self.expenses.append(Double(value)!)
self.totalExpenses = self.expenses.reduce(0, +)
self.expensesLabel.text = "Expenses: " + String(Double(self.totalExpenses)) + " €";
completion(true)
}
}
func getLeftBudget() {
getIncData { (completed) in
getExpData(completion: { (completed) in
let budgetLeft = self.totalIncome - self.totalExpenses
self.budgetMonth.text = "Budget left - \(String(budgetLeft))"
})
}
}
You can push a little the use of completion blocks and go straight forward using the function return value, avoiding context or global variables:
var income = [Double]()
var expenses = [Double]()
var totalIncome: Double = 0
var totalExpenses: Double = 0
typealias returnCalc = (Double) -> Void
func getIncData(completion: @escaping returnCalc) {
let budgetDB = Database.database().reference().child("Income")
budgetDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let value = snapshotValue["Value"]!
self.income.append(Double(Int(value)!))
// self.totalIncome = self.income.reduce(0, +)
self.incomeLabel.text = "Income: " + String(self.income.reduce(0, +)) + " €";
completion(self.income.reduce(0, +))
}
}
func getExpData(completion: @escaping returnCalc) {
let budgetDB = Database.database().reference().child("Expenses")
budgetDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let value = snapshotValue["Value"]!
self.expenses.append(Double(value)!)
// self.totalExpenses = self.expenses.reduce(0, +)
self.expensesLabel.text = "Expenses: " + String(Double(self.expenses.reduce(0, +))) + " €";
completion(self.expenses.reduce(0, +))
}
}
func getLeftBudget() {
getIncData { (inc) in
getExpData(completion: { (exp) in
let budgetLeft = inc - exp
self.budgetMonth.text = "Budget left - \(String(budgetLeft))"
})
}
}
Swift function with args... pass to another function with args
Similar as in (Objective-)C, you cannot pass a variable argument list
directly to another function. You have to create a CVaListPointer
(the Swift equivalent of va_list
in C) and call a function which
takes a CVaListPointer
parameter.
So this could be what you are looking for:
extension String {
func getLocalizeWithParams(args : CVarArgType...) -> String {
return withVaList(args) {
NSString(format: self, locale: NSLocale.currentLocale(), arguments: $0)
} as String
}
}
withVaList()
creates a CVaListPointer
from the given argument list
and calls the closure with this pointer as argument.
Example (from the NSString
documentation):
let msg = "%@: %f\n".getLocalizeWithParams("Cost", 1234.56)
print(msg)
Output for US locale:
Cost: 1,234.560000
Output for German locale:
Cost: 1.234,560000
Update: As of Swift 3/4/5 one can pass the arguments to
String(format: String, locale: Locale?, arguments: [CVarArg])
directly:
extension String {
func getLocalizeWithParams(_ args : CVarArg...) -> String {
return String(format: self, locale: .current, arguments: args)
}
}
How to pass values or data between two function with parameters in swift?
Actually I didn't understand properly your problem. But as i understand that you can use this.
func firstFunc(lat: Double, long: Double) {
//do something
secondFunc(lat: lat, long: long)
}
func secondFunc(lat: Double, long: Double) {
//do something
}
But if you want to use values after process from secondFunc you can use inout parameters.
func firstFunc(lat: Double, long: Double) {
//do something
var newLat = lat
var newLong = long
secondFunc(lat: &newLat, long: &newLong)
//new values for newLat and newLong after secondFunc
}
func secondFunc(lat: inout Double, long: inout Double) {
//do something
}
Swift how to pass closure from one function to another?
You need to escape the in parameter to the closure to start with and then when calling the closure sent to functionB you need to supply a value as argument
func functionA(closureA: (@escaping (Double) -> ())) {
functionB(closureB: closureA)
}
func functionB( closureB: (@escaping (Double) -> ())) {
closureB(3.2)
}
Example
functionA(closureA: {print($0 * 2.0)})
6.4
pass existing function as parameter to another function in Swift 3
Parameter values are let
s by default (and can't be mutated). This is the cause of your error message - it has nothing to do with being the result of toPassAsParam()
. You can get around this one of two ways, depending if you actually want to change param1
outside of the function.
If you do want param1
to mutate and keep its new value, declare it as an inout [String:String]
(the inout
keyword means it can be mutated from in the function).
If you just want to be able to change it inside the function, you can just say var param1 = param1
in the first line of your function (copy it to a variable).
A little more on the subject line of your question: you aren't passing a function as a parameter. You're passing one function's return value as a parameter to another function. If you wanted to pass the actual function to createDictionaryFromParams
, it would look something like:
// note the type of `function`
func createDictionaryFromParams(function: () -> [String:String],
param2: String,
param3: String) -> [String:String] {
var param1 = function() // now that we passed `function` in, we can call it to get a [String:String]
param1["name"] = "John"
param1["university"] = param2
return [:]
}
How to pass a function to another class in Swift
Function has a return value plus the completion , you need to change syntax of function
var inisde Sub
and the init
also
class Main {
func one() {
let test = Sub(function: two)
}
func two(val: Int, completion: ((Int, String)?)->()) { }
}
class Sub {
var function: ((Int, ((Int, String)?)->())) -> ()
init(function:@escaping ((Int, ((Int, String)?)->())) -> ()) {
self.function = function
}
}
How i can pass the completion handler to another function swift ios
Replace
self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion)
with
self.finishCreatingConversation(conversationId: conversationId, message: message) { res in
completion(res)
}
Is it possible to call a function as a parameter of another function in Swift?
Because in Swift functions are first-class types, you can pass it as an argument to another function.
Example:
func testA() {
print("Test A")
}
func testB(function: () -> Void) {
function()
}
testB(testA)
Related Topics
Downcasting Optionals in Swift: As? Type, or As! Type
Tabview Resets Navigation Stack When Switching Tabs
How to Use Userdefaults With Swiftui
What Is Difference Between Optional and Decodeifpresent When Using Decodable For Json Parsing
Swiftui Picker Separate Texts For Selected Item and Selection View
Swift 3 How to Display a Confirmation Screen Based on Mfmailcomposeresult Email Screen
Updating Time Text Label Each Minute in Widgetkit
How to Accomplish Where in Query in Cloud Firestore
Why Do Self and Self Sometimes Refer to Different Types in Static Functions
Noop For Swift'S Exhaustive Switch Statements
Difference Between Flatmap and Compactmap in Swift
Swift Structs to Nsdata and Back
How to Convert Array of Bytes [Uint8] into Hexa String in Swift
How to Parse Json With Decodable Protocol When Property Types Might Change from Int to String