cannot convert return expression of type 'String' to return type '(Int) -> String'
Solution 1
Your function header says you are returning a closure that takes an Int
and returns a String
, so that is what your function should return.
Here is an example that uses all of the inputs to construct the String
:
func doSomeThing(productName: String, productPrice: Double) -> (Int) -> String {
return { n in "\(n) \(productName)s cost \(productPrice * Double(n))" }
}
let iPhone = doSomeThing(productName: "iPhone", productPrice: 649)
print(iPhone(5))
print(iPhone(2))
Output:
5 iPhones cost 3245.0
2 iPhones cost 1298.0
Solution 2
I think the problem is you're trying to return twice in one method. Instead, just have your method take 3 parameters and return a String.
func doSomeThing(productName : String , productPrice : Double, quantity : Int) -> String {
let total = productPrice * Double(quantity)
return "The total for \(productName) is \(total)"
}
doSomeThing(productName: "my product", productPrice: 1.99, quantity: 1)
Nazmul Hasan
Hi, if you interested more about me then contact with me Skype: nazmulkp1 Mail: [email protected] Linkedin oh! You can reach me direct phone call or WhatsApp +8801924262749
Updated on June 08, 2022Comments
-
Nazmul Hasan almost 2 years
it is normal working function :
func doSomeThing(productName : String , productPrice : Double) -> String { return "good jobs" }
I might thinking function can take quantity parameter and return string
func doSomeThing(productName: String , productPrice: Double) -> (Int) -> String{ func totaPrice(quantity : Int) -> Double { return Double(quantity) * productPrice } return "Product Name \(productName) each price is \(productPrice) , total price \(totaPrice)" } let totaPrice = doSomeThing(productName: "iPhone", productPrice: 649) print(totaPrice(5)) print(totaPrice(3))
But below error throwing :
ERROR at line 14, col 11: cannot convert return expression of type 'String' to return type '(Int) -> String' return "Product Name (productName) each price is (productPrice) , total price (totaPrice)" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
how can fix this issue ?
Note :I want to do something like
Currying
function . -
Nazmul Hasan over 7 yearsno sir ! i want to trying like Currying function .
-
Nazmul Hasan over 7 yearswell ! , are there no alternative way ?
-
vacawama over 7 yearsWhat is your objection with this way?
-
Nazmul Hasan over 7 yearsi want to make it simpler and sweeter .
-
vacawama over 7 yearsThere isn't much wasted syntax in there. You can use
$0
in place ofn
in the closure and get rid ofn in
, but I personally think its cleaner to explicitly name the parameter. Does this at least capture the functionality you were looking for?