Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Make the labels on constructor parameters optional?

Let's say, for instance, you have the following code:

struct SomeStruct {
     init (arg1: String, arg2: Int){
          // Does Stuff with Variables
     }
}

// Some Point Later

var str = "fasfsad"
var integer = 343
let smth = SomeStruct(arg1: str, arg2: integer)

Is it possible to modify the SomeStruct struct to make the following line of code legal?

let smth = SomeStruct(str, integer)
like image 889
CaptainForge Avatar asked Sep 28 '14 19:09

CaptainForge


2 Answers

Yes, you can make the parameters anonymous by using an underscore for the external parameter name:

struct SomeStruct {
     init (_ arg1: String, _ arg2: Int){
          // Does Stuff with Variables
     }
}
like image 52
Nate Cook Avatar answered Oct 05 '22 12:10

Nate Cook


Here is how you can do this:

struct A {
    var a: String
    var b: String

    init(_ a: String,_ b: String) {
        self.a = a
        self.b = b
    }
}

var x = A("S", "B")
like image 30
Tomasz Szulc Avatar answered Oct 05 '22 12:10

Tomasz Szulc