Coffescript show alert when clicking on element? - coffeescript

I have this code
$ ->
$('h1').click ->
alert "I knew it!"
init()
What's wrong with it?nothing happens.

Not sure but probablt your code is formatted inproperly (what is important in coffeescript). Callback for click event must be nested (otherwise passed callback is an empty function)
$ ->
$('h1').click ->
alert("I knew it!")
init()

Related

Unable to run function with arguments in Swift

I've been trying to create a menu item for my application in swift, and by pressing different buttons on the menu I want to run different python scripts. I'm very new to Swift, and I'm guessing there's a simple mechanic I'm just missing here.
The problem is now that I'm trying to create a button, with an action being run when it is pressed.
The function call is in a Toolbar, which is in itself in a NavigationView:
ToolbarItem {
Menu {
Button("Label", action: myFunc("My string"))
} label: {
Label("Scripts", systemImage: "applescript")
}
}
Where the function myFunc is like this:
func myFunc(_ param: String) -> Void {
print(param)
}
(The integer is just a placeholder for a later value which would correspond to the path of the script I'm trying to run)
The error is:
Cannot convert value of type 'Void' to expected argument type '() -> Void'
The weird thing is that when I exclude the argument in the function call, like calling a:
func myFunc() {
print("Hello")
}
From the same location, it works just fine. Is there a limitation to the buttons like not being able to send arguments to their functions?
I've looked at different solutions, but they all seem way too complicated for this error. I saw one guide where it was because of an empty view, but this doesn't seem to be the error at hand.
The amount of buttons will later be in a ForEach. I'm however a bit conflicted regarding what the best way of storing the paths for the scripts is. I've been thinking about doing an enum with the different paths as rawValues. But I'd like different labels for the buttons than the actual paths of the files, so I'd need two values stored in the rawValues, is this possible? Like using a dictionary and using the name as key and the value as the path. Or do you have any inputs on a better way to solve this problem?
I'm very open for suggestions, the goal is just to be able to run scripts with buttons in a menu!
The problem is that you are executing the function myFunc by putting the parentheses after it, which will result in a Void value rather than a function of type () -> Void, which the Button initialiser expects.
You can fix this by wrapping your function call in a closure.
ToolbarItem {
Menu {
Button("Label", action: { myFunc("My string") })
} label: {
Label("Scripts", systemImage: "applescript")
}
}
This way you really are passing a closure of type () -> Void to the Button init (which it expects), which will only be executed on the button tap. With your previous implementation, the function was executed as soon as the Button is initialised rather than when it it tapped.
The action parameter of a Button view expects an argument of type () -> Void. This means that you need to pass a reference to a function/closure that takes no arguments and returns nothing.
That's why, when you removed the argument from myFunc (resulting in this button code:
Button("Label", action: myFunc)
it worked, because it's not calling myFunc, but simply referencing it. If you want to call myFunc with an argument, you can wrap it in a closure, like so:
Button("Label", action: { myFunc("My string") })
In this way, the closure takes no arguments and returns nothing, matching the required type.

What does the print() here do? (Printing a function that invokes another print func)

I am new to programming, particularly to the Swift language.
I'm trying to print a string that contains a print function (I use string interpolation).
I don't understand why I got a strange output from this piece of code:
func newFunc() {
print("I print a message")
}
print("Function said: \(newFunc())")
I got the following output:
I print a message
Function said: ()
The message that was called by the function was executed before the "Function said: " words.
I know I can use the return inside the function to get the correct output or use a variable to store this string, but I want to understand why I got the result described above.
Thanks in advance!
You're treating newFunc() as if it returns a useful result (something that you can interpolate into "Function said: \(here)". But it doesn't return anything, which in Swift, is equivalent to returning Void.
Void is a type that models a return of nothing. It's equivalent to the empty tuple, (). If a function doesn't declare an explicit return type (such as newFunc()), then it behaves as-if it declared a return type of Void. Any time execution of a void-returning function reaches the end of its body, it's as if there's an implicit return or return () at the end. So more explicitly written, your code behaves like:
func newFunc() -> Void {
print("I print a message")
return ()
}
print("Function said: \(newFunc())")
From here, hopefully it should be clear why you're getting the result you're seeing.
What you probably want to do instead is have newFunc() return a useful value, and have that interpolated into your string. Like so:
func newFunc() -> String {
return "I print a message" // Actually, no you don't, you return a message.
}
print("Function said: \(nenFunc())")
I think looking at call stacks will help you understand this concept more. Essentially, when you make a call to your main method (the alone print statement), main() get's placed on the stack. When a function is on the stack, it is not popped until it has been run to completion. Since your call to newFunc() happens before main completes, newFunc is then placed on top of main in the call stack. newFunc() prints, completes, and is popped. Thus, main does the same.
If the question is "why doesn't the output look like Function said: I print a message?", then the simple solution is to change the code to the following
func newFunc() {
return "I print a message"
}
print("Function said: \(newFunc())")
Here you'll see the newFunc() method does not print anything but rather returns a value to its caller, main().

How can you mark a method that it is fatal, like `fatalError`?

We have a special logging function that represents a particular type of crash, and as such, internally it calls fatalError. However, unlike fatalError, when we use it in a guard statement, it still complains we haven't exited the scope of the guard.
I checked the source code and fatalError returns -> Never so I tried that, but that didn't work either. I also didn't see any attributes applied to it that may be telling the compiler 'this is the end of the road'.
So is it possible to have your own fatalError-like method?
func myFatalError(memberName:String = #function) -> Never {
let message = "Failed in \(memberName)"
NSLog(message)
fatalError(message)
}
As pointed out by others, the issue was something on my machine specifically. The following (returning 'Never') works as expected.
func myFatalError() -> Never {
print("Doing something fatal")
}

What does () mean in Swift?

I have the following function in Swift 3
func fetchOrders(_ completionHandler: (_ orders: [Order]) -> Void)
{
ordersStore.fetchOrders { (orders: () throws -> [Order]) -> Void in
do {
let orders = try orders()
completionHandler(orders)
} catch {
completionHandler([])
}
}
}
What does _ completionHandler argument in fetchOrders mean?
What does (orders: () throws -> [Order]) mean?
PS : I am new to iOS and Swift
There's quite a lot in here, so we'll break it down one piece at a time:
func fetchOrders(_ completionHandler: (_ orders: [Order]) -> Void)
This is a function called fetchOrders.
It has one parameter (completionHandler) and returns nothing.
The first _ indicates that there is no "external name" of the first parameter. That is, you do not have to label it (in fact, you cannot). (For subtle reasons that don't really matter here, I believe the author made a mistake using _ there, and I would not have done that.)
The completionHandler is the "internal name," what the parameter is called inside the function.
The type of completionHandler is (_ orders: [Order]) -> Void. We'll break that down now.
This value is a closure that takes an [Order] (array of Order) and returns Void. Informally this means "returns nothing" but literally means it returns the empty tuple ().
The _ orders: syntax is in practice a comment. In principle the _ is an external name (but that's the only legal external name for a closure), and orders is an internal name, but in reality, closures parameters do not have names in any meaningful way, so this is purely informational.
I believe this is a poor use of the closure parameter commenting system. Since orders tells us nothing more than [Order], I would have omitted it, and made the type just ([Order]) -> Void.
Now we'll turn to the next line:
ordersStore.fetchOrders { (orders: () throws -> [Order]) -> Void in
This calls the fetchOrders method on ordersStore. We can tell from this code that fetchOrders takes a closure parameter. This is called "trailing closure" syntax in Swift, and is why I would not have used the _ for our closure. With trailing closure syntax, the external name of the parameter is not needed.
The author has provided type information here that probably wasn't necessary, but we can explore it anyway. This could likely have been written as just { orders in, but then the reader would probably have been surprised by this somewhat unusual code.
We have been passed a closure called orders that takes nothing and returns [Order] or throws an error. Basically this is a way to say that fetchOrders might fail.
The author is working around an awkwardness in Swift's throws system, which does not have a natural way to express an asynchronous action that might fail. This is one way to fix it; you pass a throwing (i.e. a possibly failing) function. I don't favor this approach, I favor using a Result enum for this case because I think it scales better and avoids possible unintended side effects, but that's a debatable point (and the Swift community hasn't really decided how to deal with this common problem).
This all leads us to:
do {
let orders = try orders()
completionHandler(orders)
} catch {
completionHandler([])
}
This is where the orders closure is evaluated. (This is very important; if orders has side effects, this is when they occur, which may be on a different queue than was intended. That's one reason I don't favor this pattern.) If the closure succeeds, we return its result, otherwise we return [] in the catch below.
In this particular case, the throws approach is slightly silly, because it's silently flattened into [] without even a log message. If we don't care about the errors, then failure should have just returned [] to start with and not messed with throws. But it's possible that other callers do check the errors.
In either case, we call the completionHandler closure with our result, chaining this back to our original caller.
This do/catch block could have been more simply written as:
let completedOrders = try? orders() ?? []
completionHandler(completedOrders)
This makes it clearer that we're ignoring errors by turning it into an optional, and avoids code duplication of the call to completionHandler.
(I just add the extra let binding to make the code a little easier to read; it isn't needed.)
The completionHandler argument means that the expected parameter (named completionHandler) must be a function that takes a list of Order objects and does not return any value.
completionHandler is the a variable name. In this specific example, this variable is a callback. You know is a callback function because (orders: [Order]) -> Void is it's data type; in this particular case, said data type is a function that receives an array of Order objects in a variable _orders and doesn't have a return value (the Void part).
TL;DR:
it's the variable name, of type:
function which receives an array of Order as a parameter and acts as a callback.

What is the actual meaning of " ! " prefix in Swift?

I want to know about prefix !. I have created an app, and it has tableView. And I have used setEditing:animated property for editing a tableView, it allows multiple selection. When user start selecting? We need to cancel segue operations. Of course we need to override shouldPerformSegueWithIdentifier method. Here's my code
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
return !editing
}
Firstly I've tried to use return editing. Xcode does not gave me any errors even run time errors. Everything seems to works just fine. But segues are still works. And then I've tried to use with prefix return !editing. Works perfect! What's the actual meaning of this prefix ! ?
Thanks
The ! operator is the logical NOT of a boolean value; i.e. !true becomes false, !false becomes true.