Given a struct S defined in this way
struct S {
let a : String
let b : Int
let c : Bool
}
and a function sConstructorFun
func sConstructorFun(#a:String, #b:Int, #c:Bool) -> S {
return S(a:a, b:b, c:c)
}
I can use both sConstructorFun(a:"", b:1, c:false) and S(a:"", b:1, c:false) to get the following S value (as the REPL outputs it)
S = {
a = ""
b = 1
c = false
}
So S and sConstructorFun have the very same interface and unsurprisingly return the same result.
However, a sFactory function defined as follows
func sFactory(f:(String, Int, Bool) -> S) -> S {
return f("foo", 42, false)
}
can only be used with the sConstructorFun but not with S directly:
REPL> sFactory(sConstructorFun)
$R2: S = {
a = "foo"
b = 42
c = false
}
and
REPL> sFactory(S)
repl.swift:18:1: error: cannot invoke 'sFactory' with no arguments
sFactory(S)
^
repl.swift:18:9: note: expected an argument list of type '((String, Int, Bool) -> S)'
sFactory(S)
^
Is there any way of using the default constructor of a struct (S in this example) as a function (without defining a new function/closure to do so)?
S = { a = "", b = 1, c = false }.Sis the struct, then you useSas a left value. The syntax does not appear to be a valid Swift constructfunc sConstructorFun(#a:String, #b:Int, #c:Bool) -> Stofunc sConstructorFun(a a:String, b b:Int, c c:Bool) -> Sbecause I thought that means something different. I'm really sorry about that and I will now reapply that edit.