I'm still learning Swift, but extrapolating from what I might do in Python
or Ruby...

protocol MyProtocol { ... }

func myFunction(generator: (MyParameterType) -> MyProtocol) {
  for ... {
    let p : MyParameterType = ...
    if not p special { continue }

    let obj = generator(p)
    ...
  }
}

class Foo : MyProtocol {}

myFunction() { p in Foo(p) }

You should always be looking for the idiomatic way to do something in a
language, and not just translate line from line your old code. There's
probably an even slicker way to do this, but here's what immediately popped
into my head. It's even more flexible than your Obj-C example since the
closure captures the caller's context, and you can use all that to
construct Foo if you want, yet type safety is always assured.


On Sat, Aug 16, 2014 at 6:32 AM, Gerriet M. Denkmann <gerr...@mdenkmann.de>
wrote:

> How to translate into Swift:
>
> - (void)myFunctionWithClass: (Class)someClass
> {
>         for(...)
>         {
>                 p = ...
>                 if ( p is not special ) continue;
>
>                 id <MyProtocol> aClass = [[ someClass alloc]
> initWithParameter: p ];
>                 ... do something with aClass ...
>         }
> }
>
> Assuming that someClass is costly to initialize and myFunctionWithClass
> does so only under certain circumstances.
> Or that myFunctionWithClass creates many instances of someClass.
>
> Assuming also, that there is an unlimited number of classes (all
> implementing MyProtocol).
>
> Which means that there is no way that the caller of myFunctionWithClass
> could create a someClass and pass it to the method.
>
> How to do this in Swift?
>
> Gerriet.
>
>
> _______________________________________________
>
> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
>
> https://lists.apple.com/mailman/options/cocoa-dev/stephen.butler%40gmail.com
>
> This email sent to stephen.but...@gmail.com
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to