Documentation comment for multi-return-value functions in Swift3 - swift

Swift3 supports functions with multiple return values, for example
func foo(param1: Int, param2: Double) -> (retA: String, retB: [Int]) {
// ...
}
when creating documentation comment for this function, we can use
/// function `foo` .....
///
/// - Parameters:
/// - param1: xxx
/// - param2: xxx
to create statements of param1 and param2. Then, how to create statements for retA and retB? If I use
/// - Returns:
/// - retA: xxx
/// - retB: xxx
the quick help just treat retA and retB as two Markdown items, and cannot get the same effect with param1 and param2.

I don't believe it's possible to get what you're trying to do.
This is because although you can use multiple return types, it's internally transformed into a tuple (which is a single value). Taking this into account and the fact that the quickhelp documentation says:
The Parameters section lists the parameters for a method or function.
The Returns section documents any return value for a method or function.
Notice how the parameters is shown as a plural while the return is a single value (in this case a tuple).
You might have better luck simply formatting the return using markdown to give it a nicer format.

Related

Searching for functions by type signature & return value

I was in the shower just now and I thought: it would be cool to be able to search for appropriate functions by their type and return value with a given set of appropriate arguments. Consider,
I'm writing some code in VSCode, for example, and I have a string a and an object o like { name: string }. I want to do something like, join the string and the object's name, maybe with , as a delimiter. I am in some big codebase and I have no idea if such a function exists, or what it would be called if it did. Instead of reinventing the wheel, I type
fn(a, o): string
and a dropdown menu appears with a list of every function in the codebase of the form string -> { name: string } -> string, along with the return value of that function given my particular a and o. So with a = "hello" and o = { name: "Bob" }, in the list I might see,
greet(greeting, user) -> "Hello, Bob"
and then if I clicked this, the fn I had typed above would autocomplete to greet.
I think this would greatly improve, for example, discoverability of common helpers in large codebases. You could maybe configure it with a few folders, and make sure none of those functions had side-effects.
Does this exist somewhere as a plugin? For any language, I'm not picky. I'm aware of Hoogle. This would be like, Hoogle but with return values.

Adding classes to micropython module

In reference to adding module in micropython, I was trying to create a class which has a local method. In the documentation it is given how to add local methods and that the first argument should be of mp_obj_t type which is the data struct itself. However, I was asking how can I pass extra parameters like other methods? I tried using mp_obj_t * args as second argument but STATIC MP_DEFINE_CONST_FUN_OBJ_1 gives error. I tried the same with STATIC MP_DEFINE_CONST_FUN_OBJ_VAR but it does not support passing mp_obt_t as first argument as STATIC MP_DEFINE_CONST_FUN_OBJ_VAR needs an int. I am quite new, so I was asking how to add methods to classes which can accept arguments?
You need MP_DEFINE_CONST_FUN_OBJ_2, since you have 2 arguments.
Something like
STATIC mp_obj_t my_class_func(mp_obj_t self, mp_obj_t arg) {
if (MP_OBJ_IS_SMALL_INT(lhs)) {
const mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(arg);
//...
} else {
//oops, not an int
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(my_class_func_obj, my_class_func);
The best source of samples like this is the source code btw.
To eleaborate on #stijn answer ~ when creating a class, all the MP_DEFINE_CONST_FUN_OBJ_XXXXXX defines work the exact same as they would if you weren't creating a class. The only difference is the first argument of ACTUAL arguments will always refer to self
Here's an example:
mp_obj_t Class_method(mp_uint_t n_args, const mp_obj_t *args) { ... }
That is the standard candidate for:
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(Class_method_obj, 1, 3, Class_method);
However, in this case args[0] will be self.
Let's have another example.
mp_obj_t Class_method(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { ... }
That's a prime candidate for this define
MP_DEFINE_CONST_FUN_OBJ_KW(Class_method_obj, 2, Class_method);
The only difference in this case is that the first index of allowed_args needs to automatically be handled as self. Nothing about how you do these things changes, except now the first ACTUAL argument (ie not including n_args or any other "helper" argument) needs to automatically be considered as self. That being said, you will NEVER use MP_DEFINE_CONST_FUN_OBJ_0 with a class method. '_0' means "zero arguments" and a class method will never have zero arguments because it will ALWAYS at least have self. This also means that you have to add one to however many expected arguments you have on the python end. If your python version accepts 3 arguments ~
(red, green, blue)
then your C_MODULE define has to start at 4 because it's going to get
(self, red, green, blue)

#helper.repeat in PlayFramework

I don't understand how to describe #helper.repeat in play2.2.1.
#helper.form(action = routes.Application.send) {
#helper.repeat(
field = form1("input"), min = 3
) {fld =>
#helper.inputText(
field = fld, '_label ->"input"
)
}
}
It is the part fld => #helper.inputText(field = fld) that I can't understand.
What does it mean?
I know Java, so I assume it is a functional writing, but in above code, where does the variable fld come from?
And why the tip of the arrow indicates #helper.inputText(field = fld)?
why is fld the value of field in #helper.inputText?
I have googled, but I couldn't find an enough explanation for a beginner.
I am not sure of Scala's grammar.
Please explain above code for a beginner?
Original Answer
This seems to be a bit overcomplicated. There is no need to assign values by hand. Usually you would write a repeater like this:
#helper.repeat(form1("input"), min = 3) { fld =>
#helper.inputText(fld, '_label ->"input")
}
In functional programming this is a so called higher-order function. You may know other scala built in higher-order functions like map, filter or foreach. #helper.repeat is very similar to foreach. form1("input") refers to a collection of values you want to display. min = 1 tells the repeater to show at least one field. Finally within { fld => ... } you iterate over all values defined in your collection.
In other words: { fld => ... } is just an anonymous function that takes a single Field parameter (fld) and displays a text input for that specific field.
Follow Up
Ok, I'm trying to follow up your questions from the comments. Let's start by the signature of helper.repeat. There is no magic involved here, it's just a regular Scala function:
helper.repeat(field: Field, min: Int)(fieldRenderer: (fld: Field) => Html): Seq[Html]
In Scala, functions can have multiple parameter lists. Here we have two. The first parameter list takes two parameters: field and min. The second parameter list takes a single function as parameter: fieldRenderer. fieldRenderer itself takes again a single parameter (fld) and returns Html.
The important thing is, you are not passing "data" but a function instead. To clear this up:
The signature fieldRenderer: (fld: Field) => Html
is equal to def fieldRenderer(fld: Field): Html
This means, you can do anything within this function, as long as it returns Html. That's exactly what happens in the example at the very top. You pass a Field and return Html. You do that by calling #helper.inputText.
Now repeat first gets a List[Field] from field you pass as first parameter. This list corresponds to the String List of your container class. Also repeat ensures there is at least one element in that list. This is, because you passed 1 as min. Then the function fieldRenderer is applied to all elements in our list.
A pseudo code implementation of repeat could look like this:
def repeat(field: Field, min: Int)(fieldRenderer: (fld: Field) => Html): Seq[Html] {
val list: List[Field] = field.getFields
var output: List[Html] = List()
for (i = 0; i < list.length; i++) {
val element: Field = list.get(i)
val html: Html = fieldRenderer(element)
output += html
}
return output
}

What is the new format of documentation comments in Swift 2? (XCode 7 beta 3)

There is this great article by Nate Cook and Mattt Thompson that describes the format of documentation comments in Swift.
However, since Swift 2 in XCode 7 beta some parts of it do not seem to work any more. For example :param: and :returns: do not produce desired result (they are simply rendered as-is instead).
Other parts seem do keep working, though (i.e. both types of comments in /// ... or /** ... */ style, code-blocks, lists), but no way to mark up the documentation into similar sections like the core API has.
Does someone know if there is a way to highlight method parameters and returned results (what :param: and :returns: did in the past) in documentation comments in Swift 2?
If you're looking for Symbol Documentation Markup Syntax, meaning if you want to know the new syntax (Xcode 7) to write documentation for your methods using Markdown, there is the Markup Formatting Reference on Apple's website.
Here's how you define a Block Comment :
/**
line of text with optional markup commands
…
line of text with optional markup commands
*/
And here's an example of a comment with the most important tags :
/**
Just testing documentation using Markdown
- returns: Bool
- parameter param1:String
- parameter param2:String
- Throws: error lists
*/
And here's the short format
/// line of text with optional markup commands
What’s new in Xcode 7. gives a hint
Markdown comments shown as rich text in Quick Help with embedded
images and links.
and the Xcode 7 beta release notes state:
Swift documentation comments use a syntax based on the Markdown
format, aligning them with rich comments in playgrounds. (20180161)
followed by a short description.
As an example,
/**
Repeats a string `times` times.
:param: str The string to repeat.
:param: times The number of times to repeat `str`.
:returns: A new string with `str` repeated `times` times.
*/
func repeatString(str: String, times: Int) -> String {
return join("", Array(count: times, repeatedValue: str))
}
from http://nshipster.com/swift-documentation/ would now be written as
/// Repeats a string `times` times.
/// - Parameters:
/// - str: The string to repeat.
/// - times: The number of times to repeat `str`.
/// - returns: A new string with `str` repeated `times` times.
func repeatString(str: String, times: Int) -> String {
return Repeat(count: times, repeatedValue: str).joinWithSeparator("")
}
Or with multiline comment:
/**
Repeats a string `times` times.
- Parameter str: The string to repeat.
- Parameter times: The number of times to repeat `str`.
- returns: A new string with `str` repeated `times` times.
*/
func repeatString(str: String, times: Int) -> String {
return Repeat(count: times, repeatedValue: str).joinWithSeparator("")
}
For more information on Markdown, see
https://en.wikipedia.org/wiki/Markdown
http://daringfireball.net/projects/markdown/
and much of
Playground Markup Format for Comments
applies to inline documentation comments as well.
For example, you could add
**Important:** `times` must not be negative.
where "Important" is rendered strong.
In Xcode 7 beta 4 a list of parameters can only be written like this:
- parameter str: The string to repeat.
- parameter times: The number of times to repeat `str`.
(This should be a comment on Martin Rs post but I don't have the reputation to do so.)

How do I set up a slot (event handler) that takes parameters, using gtk.go.Connect()?

I am using GTK bindings for Go.
Trying to connect a gtk.RadioButton toggle signal to a function. This code works fine:
...
radioButton.Connect("toggled", doRadioToggle)
func doRadioToggle() {
fmt.Println("toggled")
}
...
When radioButton is toggled, doRadioToggle is called - Good.
But I want to connect to a function that takes a parameter, for example:
func doRadioToggle(button *gtk.RadioButton) {
fmt.Println(button.GetState())
}
The gtk.go.Connect() function has this signature:
func (v *Widget) Connect(s string, f interface{}, datas ...interface{})
Based on what I know from gtkmm, I tried code like this (the go binding has apparently greatly simplified the call to connect())
radioButton.Connect("toggled", doRadioToggle, radioButton)
The third argument passed inconnect() - radioButton - corresponding todatasin
gtk.Connect(s string, f interface{}, datas ...interface{})
which I understood to mean data arguments to be passed to the slot.
But with this code, the doRadioToggle() handler never gets called, and I immediately exit with a panic:
panic: reflect: Call using *glib.CallbackContext as type *gtk.RadioButton
My question: How do I set up slot (event handler) that takes parameters using gtk.go.Connect()?
Based on response from the amazing mattn on GitHub:
https://github.com/mattn/go-gtk/blob/master/example/demo/demo.go#L58
Adopted, tested and working:
import(
...
"github.com/mattn/go-gtk/glib"
)
...
func ButtonHandler(ctx *glib.CallbackContext) {
fmt.Printf("Button Handler: %v\n", ctx.Data().(*gtk.RadioButton).GetState())
}
aRadioButton.Connect("toggled", ButtonHandler, aRadioButton)
...
Thedatasarguments inconnect()must be passed using*glib.CallbackContext in the handler's signature, then, in the handler code, use type assertion to grab the actual arguments .
The documentation is not clear about how to pass additional data directly; perhaps simply use a closure instead.
https://godoc.org/github.com/mattn/go-gtk/glib#CallbackContext