Fawkes
Fawkes

Reputation: 3941

Can I define a function header directly with a typealist tuple?

Just for fun.

For example I have different actions on user which I want to separate intentionally in different functions.

  1. request friendship
  2. block friendship
  3. cancel friend request
  4. ...

And all this functions (because I want to make them distinct) receive the same parameters

  1. nickname
  2. a completionBlock

so in general I would have a lot of this functions:

  1. class func requestFriend(nickName : String, withCompletitionHandler completitionHandler : (status : Bool) -> Void)
  2. class func acceptFriend(nickName : String, withCompletitionHandler completitionHandler : (status : Bool) -> Void)
  3. ...

Now what would be really nice to be able to do, would be something like:

typealias UserActionTupleParameter = (nickName : String, completitionHandler : (status : Bool) -> Void)

Define the function maybe as :

class func acceptFriend => UserActionTupleParameter
{
}

And use as:

acceptFriend(myTupleVariable)

Instead of having the function def:

class func acceptFriend(parametersTuple : UserActionTupleParameter)

that will only result in calling the function as:

class func acceptFriend((myString, myBlock))

Maybe I'm missing something, or I messed with parameters naming which does not let me pass the parameters without the tuple "()", but I cannot make the Xcode 7 Swift 2 accepting my intention.

I specifically intend to enforce using the tuple typealias definition as a func parameter in the func definition.

Because I know I can define the func like:

func test (string : String, block : Block)

and then create the tuple as:

let tuple = (myString, myBlock)

and call the function as:

test(tuple)

Some ideas?

Upvotes: 0

Views: 156

Answers (1)

Price Ringo
Price Ringo

Reputation: 3440

Is this what you are looking for?

typealias UserAction = (nickname: String, completionHandler: Bool -> Void)

func testA(userAction: UserAction) -> Void {
  NSLog("testA called for user \(userAction.nickname)")
  userAction.completionHandler(true)
  NSLog("testA exited")
}

func testB(userAction: UserAction) -> Void {
  NSLog("testB called for user \(userAction.nickname)")
  userAction.completionHandler(false)
  NSLog("testB exited")
}

let myAction = UserAction("Willy") {
  status in NSLog("myAction status is \(status)")
}

Here is how it runs in my Playground. enter image description here

Upvotes: 1

Related Questions