The line below, at SQLHandler.translateQuery("Do mysql stuff"), is throwing the error: '(String) -> String' is not convertible to 'SQLHandler'. Why is it doing this? Thank you in advance.
Code 1 (Used wherever and whenever needed)
var query: String = "mysql stuff"
SQLHandler.sendQuery(SQLHandler.translateQuery("domain and \(query)"))
Code 2, SQLHandler.swift (Called whenever needed)
import Foundation
class SQLHandler {
func translateQuery(queryToTranslate: String) -> String{
println(queryToTranslate)
return queryToTranslate.stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.LiteralSearch, range: nil)
}
func sendQuery(query: String){
println(query)
let url = NSURL(string: "url and query goes here")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in })
task.resume()
}
}
You are calling an instance method on the class itself.
Either create an instance and call the method:
var sqlHandler = SQLHandler()
sqlHandler.translateQuery("domain and \(query)")
or define the methods as class methods :
class func translateQuery(queryToTranslate: String) -> String ...
class func sendQuery(query: String) ...
Related
Look at my code here
package main
import (
"fmt"
)
type iFormatter interface {
SetName(name string)
Format() string
}
type BaseFormatter struct {
name string
}
type Formatter struct {
BaseFormatter
}
func (f Formatter) SetName(name string) {
f.name = name
}
func (f Formatter) Format() string {
return "formatted " + f.name
}
func main() {
var formatters = []iFormatter{Formatter{}}
formatters[0].SetName("KARL")
fmt.Println(formatters[0].Format())
}
I don't understand, why the field "name" is not setted after calling SetName.
Here is the link for playground https://play.golang.org/p/Jkcjv_hFRC.
The SetName() method should be on a pointer, not value. Currently the f is a copy of the formatters[0] and changes to f are not propagated to formatters[0].
The code below should do the trick.
func (f *Formatter) SetName(name string) {
f.name = name
}
...
var formatters = []iFormatter{&Formatter{}}
You don't need to change the Format() method to pointer receiver though in your case it could be better to do it.
See: https://play.golang.org/p/rFmCZesbTB
In your code, changing these two methods like this should make it work as you expect:
func (f *Formatter) SetName(name string) {
f.name = name
}
func (f *Formatter) Format() string {
return "formatted " + f.name
}
and using a pointer as
var formatters = []iFormatter{&Formatter{}}
https://play.golang.org/p/eSX3mXys-a
Basically, using a pointer receiver instead of a value receiver. Using a value receiver works on a copy of the struct instead of the original struct.
Im new to GoLang and cannot figure out whats wrong in the code below. What i'm trying to do is "Create and return Printer function on the fly"
type Salutation struct { name string
greeting string
}
type Printer func(s string) string
func Greet2(salutation Salutation, do func(string)) (string){
do(salutation.name + " " + salutation.greeting)
return "Done"
}
func createPrintFunction(custom string) Printer {
return func(s string) string {
return "hello"
}
}
func pluralSightModule1Closures1(w http.ResponseWriter, r *http.Request) {
var s = Salutation{"Joe", "Hello"}
res := Greet2(s, createPrintFunction("!!!"))
w.Header().Set("Content-Type", "application/json")
w.Write([]byte (res))
}
I get the following compilation error
cannot use createPrintFunction("!!!") (type Printer) as type func(string) in argument to Greet2
The problem is the signatures don't match. That includes the return type.
Greet2 wants func(string) but createPrintFunction returns func(s string) string. Note that Greet2's returns nothing, but the createPrintFunction function returns a string.
You'll have to decide how to make them match. You probably want to use the return value in Greet2 for something better than "Done".
func Greet2(salutation Salutation, do func(string) string) string {
return do(salutation.name + " " + salutation.greeting)
}
Since you've defined type Printer func(s string) string its best to use it consistently to avoid this sort of problem. Greet2 takes a Printer and createPrintFunction returns a Printer. Then if Printer changes things will still work.
func Greet2(salutation Salutation, do Printer) string {
return do(salutation.name + " " + salutation.greeting)
}
...but the do generated by createPrintFunction doesn't use its arguments. It's hard to advise what it should do because much of this code just passes its arguments straight through, or ignores them.
Anyhow, the signatures have to match.
Solution:
func Greet2(salutation Salutation, do Printer) (string){
return do(salutation.name + " " + salutation.greeting)
}
type Printer func(string) string
func createPrintFunction(custom string) Printer {
return func(s string) string {
return s
}
}
func pluralSightModule1Closures1(w http.ResponseWriter, r *http.Request) {
var s = Salutation{"Joe", "Hello"}
res := Greet2(s, createPrintFunction("!!!"))
w.Header().Set("Content-Type", "application/json")
w.Write([]byte (res))
}
i just made one wrapper class for share helper my code is as follow.
let activityVC = UIActivityViewController(activityItems: [message], applicationActivities: nil)
activityVC.setValue(subject, forKey: "subject")
activityVC.completionWithItemsHandler = {(activityType: String!, completed:Bool, objects:[AnyObject]!, error:NSError!) in
}
fromVC.presentViewController(activityVC, animated: true, completion: nil)
problem starts here, UIActivityItemSource methods not being call
override func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
switch activityType
{
case UIActivityTypeMail:
return msg
case UIActivityTypeMessage:
return msg
case UIActivityTypePostToFacebook:
return msg
case UIActivityTypePostToTwitter:
return strTwitterShare
default:
return msg
}
}
thanks for help
It should work if you use let activityVC = UIActivityViewController(activityItems: [self], applicationActivities: nil)
... then your message is provided inside your itemForActivityType method.
I can create method alias for an usual method:
func method1() {
fmt.Println("method1")
}
var Method1 = method1
But cannot do the same for a method receiver:
type Person struct {
Name string
}
func (p *Person) methodReciver() {
fmt.Println("method reciver")
}
var MethodReciver = methodReciver
In this case I got the error on line var MethodReciver = methodReciver:
undefined: methodReciver
Full code:
package main
import (
"fmt"
)
type Person struct {
Name string
}
func method1() {
fmt.Println("method1")
}
var Method1 = method1
func (p *Person) methodReceiver() {
fmt.Println("method receiver")
}
var MethodReceiver = methodReceiver
func main() {
method1()
Method1()
p := Person{"Nick"}
p.methodReceiver()
p.MethodReceiver()
}
Playground
Is it possible to create a method alias for methodReceiver?
Basically you have 2 options:
1. Using a Method Expression
Which has the form of ReceiverType.MethodName and it yields a value of a function type:
var MethodReceiver = (*Person).methodReceiver
MethodReceiver just holds the function reference but not the receiver, so if you want to call it, you also have to pass a receiver (of type *Person) to it as its fist argument:
var p = &Person{"Alice"}
MethodReceiver(p) // Receiver is explicit: p
2. Using a Method Value
Which has the form of x.MethodName where the expression x has a static type T:
var p = &Person{"Bob"}
var MethodReceiver2 = p.methodReceiver
A method value also stores the receiver too, so when you call it, you don't have to pass a receiver to it:
MethodReceiver2() // Receiver is implicit: p
Complete Example
Try it on Go Playground.
type Person struct {
Name string
}
func (p *Person) printName() {
fmt.Println(p.Name)
}
var PrintName1 = (*Person).printName
func main() {
var p1 *Person = &Person{"Bob"}
PrintName1(p1) // Have to specify receiver explicitly: p1
p2 := &Person{"Alice"}
var PrintName2 = p2.printName // Method value, also stores p2
PrintName2() // Implicit receiver: p2
}
Output:
Bob
Alice
Yes. You can make an alias like this:
var MethodReceiver = (*Person).methodReceiver
When you call it, you have to provide a pointer to a person object as the first argument:
MethodReceiver(&p)
You can see this in action on the Go Playground.
This is called method expression var MethodReceiver = (*Person).methodReceiver
Playground
I have an NSFormatter in Swift, which is attached to an NSTextField. It prevents illegal characters from being entered, but when I try to access the value of the next field it gives a nil value.
Below is the class:
class PSEntryNameFormatter : NSFormatter {
override func stringForObjectValue(obj: AnyObject?) -> String? {
if obj == nil {
println("stringForObjectValue: obj is nil, returning nil")
return nil
}
if let o = obj as? String {
println("stringForObjectValue: obj is string, returning \(o)")
return o
}
println("stringForObjectValue: obj is not string, returning nil")
return nil
}
override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
println("getObjectValue: \(string)")
let obj = string
return true
}
override func isPartialStringValid(partialString: String?, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
if let s = partialString {
var illegals : String = join("",s.componentsSeparatedByCharactersInSet(PSEntryNameFormatterCharacterSet))
var goods = s.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: illegals))
let newString : NSString = join("", goods)
if String(newString) == s {
println("isPartialStringValid: partial string ok")
return true
}
}
println("isPartialStringValid: partial string bad")
return false
}
}
And here is how I try to access:
func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
println("Text should end editing")
if (control == nameTextField) {
var name = nameTextField.objectValue as String
setObjectName(name)
}
return true
}
For debugging I add the println statements, and here is what happens when the textfield is set to 'Template' and then I delete two characters:
stringForObjectValue: obj is string, returning Template
stringForObjectValue: obj is string, returning Template
isPartialStringValid: partial string ok
getObjectValue: Templat
isPartialStringValid: partial string ok
getObjectValue: Templa
Then I press enter:
getObjectValue: Templa
Text should end editing
getObjectValue: Templa
stringForObjectValue: obj is nil, returning nil
getObjectValue:
stringForObjectValue: obj is nil, returning nil
stringForObjectValue: obj is nil, returning nil
fatal error: unexpectedly found nil while unwrapping an Optional value
And then it crashes on the line when I cast to string. Obviously I can prevent the crash, but first I want to find out why it is returning nil. Any help very much appreciated!
The problem is in your getObjectValue function.
You should be assigning the value in this manner:
obj.memory = string
instead of
let obj = string
I have a similar problem and got a partial fix:
override func stringForObjectValue(obj: AnyObject) -> String? {
if let desc = obj.description {
println("sFO=\(obj)")
} else {
println("sFO=nil")
}
return obj.description
}
But each time I tab out of the field its contents is set to nil again. Still stuck with that. I had no issue with the analog OC code.