Re: Class in Swift
Re: Class in Swift
- Subject: Re: Class in Swift
- From: "Stephen J. Butler" <email@hidden>
- Date: Sat, 16 Aug 2014 16:10:05 -0500
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 <email@hidden>
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 (email@hidden)
>
> 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:
>
>
> This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden
References: | |
| >Class in Swift (From: "Gerriet M. Denkmann" <email@hidden>) |