Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Did they really not sandbox the playground? Ugh. Well, this is why it's a beta.

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

tstm posted:

The optimizer seems to do some really weird things for me.

This is all really awesome, and I filed it (rdar://17160101) for us to look into and consider as a benchmark.

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!
In addition to a metaobject protocol I wish that Swift offered traits (aka roles) as well. On the surface they're like protocols that can provide default implementations of some of its methods (usually building on other methods that the trait requires). At a deeper level they become a very attractive way to decompose your problems into fundamental building blocks.

Here's a motivating example of where I would have used roles in Objective-C, if I had them.

I'm writing a 2D tile-based game. I have an Action base class with dozens and dozens of subclasses. Many, but not all, Actions have an Actor. So I have a generic ActionWithActor subclass that provides an actor property and related methods, etc. Many, but not all, Actions have a Direction. So I have an ActionWithDirection subclass that provides a direction property and related methods, etc. (You can imagine that I have other reusable components like Origin, Target, Magic, Instant, etc)

Some actions have both an Actor and a Direction. Now what do I do? No way I want to go anywhere near multiple inheritance. At best I can subclass ActionWithActor and reimplement the direction parts. That works well enough except the compiler can get grumpy about those direction-based methods.



Of course, I'd face the same exact problems if I were to subclass ActionWithDirection and reimplement the actor parts.

The alternative, more Cocoa-ish way might be to use protocols for ActorAction and DirectionAction. That would be enough to satisfy the compiler that my types are well-formed, but now I'm back to square one for code reuse. Every single one of these Action subclasses need to reimplement these actor- and direction-related properties and methods. At that point the protocols are really only there to satisfy the compiler. They don't work for me.

Traits offer a robust, solution to these problems without compromising type safety. We use them in the Perl/Moose world extensively and it's one of the two things (along with the MOP) that make modern Perl even remotely usable.

rjmccall: Would you like me to continue? Or has your team already evaluated and rejected traits as a feature for Swift? Or are protocols that much beefier than Objective-C's that I've already got what I want? If this is new to you I'm more than happy to start filing radars loaded with citations both for their theoretical and practical value!

Filburt Shellbach fucked around with this message at 22:49 on Jun 4, 2014

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

I'm the 9to5mac news article.

LASER BEAM DREAM
Nov 3, 2005

Oh, what? So now I suppose you're just going to sit there and pout?
This is probably a stupid question, but how can I read input from the console for a command line swift program?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Filburt Shellbach posted:

rjmccall: Would you like me to continue? Or has your team already evaluated and rejected traits as a feature for Swift? Or are protocols that much beefier than Objective-C's that I've already got what I want? If this is new to you I'm more than happy to start filing radars loaded with citations both for their theoretical and practical value!

I think that what you're doing in your wall o' text can be reasonably modeled with just default implementations in protocols, which is something we want to do.

Doctor w-rw-rw-
Jun 24, 2008
After lunch, I asked about reflection/proxies at the Swift lab (Axiem was interested and I was curious), and it didn't sound like there's much of a story for it in Swift yet. I suggested that rather than full-blown NSProxy support, something akin to Java's Proxy class might be worthwhile. Rather than proxying entire classes, dynamically instantiating an object that satisfies one or more interfaces might help keep Swift in a type-safer world than ObjC (and keep ARC working as expected), while also allowing things such as mocking.

(tl;dr: the Proxy class creates an object that delegates to an associated invocation handler class, which has a single function that gets called with the invocation's signature, etc. and handles it completely.)

They suggested filing a radar with a concrete suggestion such as the above. (Axiem, get on it)

Doctor w-rw-rw- fucked around with this message at 00:50 on Jun 5, 2014

ultramiraculous
Nov 12, 2003

"No..."
Grimey Drawer
So is having a recursive inner function supposed to be possible? I was trying to write an inner function that called itself, and got a full a full-on compiler abort. Just this simple example breaks things:

code:
class Example {
	
	//LLVM ERROR: Broken function found, compilation aborted!
	func breaksCompiler() {
		func innerFunction() {
			innerFunction()
		}
	}

	//Error: "Variable used within it's own initial value"
	func givesError() {
		let innerFunction: ()->Void = {
			innerFunction()
		}
	}

}
The error case was my second attempt, and the error is reasonable. I'm just wondering if the first case should give an error and doesn't, or if it should be working.


Edit: Radar'd the compiler error (rdar://17165028)

ultramiraculous fucked around with this message at 01:11 on Jun 5, 2014

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
It should work; it's worth a bug.

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

So how does the time traveling debugger work? I'm also interested.

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

rjmccall posted:

I think that what you're doing in your wall o' text can be reasonably modeled with just default implementations in protocols, which is something we want to do.

Excellent. That would indeed be enough for me. Default implementations get you the most useful 80% of traits.

The other 20% of the traits paper is still useful, if you want more ideas on how to take protocols further, or for insight into the new problems that might arise when you have protocols providing implementations.

For example, what if a class consumes two protocols which provide different implementations of a method with the same signature? (It's not that outlandish to think, say, position could have more than one meaning). Traits offer a solution: that situation becomes a compile-time error that is resolved by adjusting the class consuming the composite trait. The class can either exclude the method from one of the traits (so the other is included as normal), or offer its own implementation of that method, which can call the two conflicting trait methods as it wishes. Which is as simple as calling the fully-qualified method names of each trait, which is familiar in Swift.

The traits design came from a team working in Smalltalk, and they have a case study in refactoring the Smalltalk collection class hierarchy to use traits. tl;dr, it went extremely well.

quote:

The traits that we have written will also allow us to construct new kinds of collection in the future, simply by composing the necessary traits and implementing a few glue methods. For example, we can build a class PluggableBag by using the trait TPluggableAdaptor in a subclass of Bag, and we can create immutable variants of collections by omitting the mutable interface traits. In addition, the availability of these traits frees the implementors of the collections framework from the need to ship pre-built collection classes for rarely used special cases.

There are a couple other features that are useful when you have all the other pieces. before/after/around method hooks (a generalization of willSet and didSet that can fire off any method - see CLOS) amplify the power of what traits can do (and are convenient for subclasses too). Applying traits at runtime to create one-off subclasses of existing classes, usually for an individual object, is useful for debugging or constructing classes a la carte. Going perhaps a bit too far, there are also parameterized roles which generate traits at runtime.

If you have all three of these pieces, you could write, say, a reasonable approximation of KVO, in userspace, as a single, well-defined module. Here's a rough sketch:

code:
protocol KVO(properties: String[]) { // this protocol takes an array of properties to observe
    // conceptually, the body of the protocol is executed for each class that consumes the protocol
    // so we can loop over the parameters and generate hooks for each one
    // it's not *that* different from Swift's enum with associated values

    for property in properties {
        // generate before and after hook methods for each property in the array
        // these methods names of course can't be hardcoded,
        // since each consumer of the protocol chooses its own properties

        before "set\(property)" { publish("will-set-\(property)") }
        after "set\(property)" { publish("did-set-\(property)") }
    }
}


// this creates a one-off subclass of myView
// wraps the setBounds and setCenter methods with before- and after-hooks
// then changes the class of myView to that subclass
myView.meta.applyProtocol(KVO(["bounds", "center"]))
// note that this is happening at runtime


// could also inspect all objects that are, or descend from, a particular class
UIView.meta.apply(KVO["bounds", "center"]))


// this instance of the KVO protocol observes these different properties instead
myModel.meta.applyProtocol(KVO(["firstName", "lastName", "email"])
I'm pretty enthusiastic about traits because experience shows again and again they're a natural fit for so many problems.

*mic drop*

Filburt Shellbach fucked around with this message at 03:23 on Jun 5, 2014

BennyGsGhost
Jun 27, 2002

Low P/B or Bust
Pillbug
I converted a tiny project (it just adjusts bars on screen based on motion data) I had been messing with and found Swift really easy to use, much easier than Obj-C. I read most of the Swift book but I'm also extremely new to dev, I could easily see more experienced people having an even easier time.

So from this newbie's perspective, it's been great. Also appreciate rjmccall taking time to answer questions here!

Scaevolus
Apr 16, 2007

rjmccall posted:

Hmm. We should definitely provide operators that return an overflow bit back. I'll file that.
What happens when you cause an overflow with normal arithmetic, though? It specifies that it's trapped and reported as an error, but is there any way for a user to handle that?

The language used in the documentation is somewhat confusing -- normally arithmetic overflow behaviors are truncate/wrap, saturate, trap/except, widen, undefined.

Truncating addition is a clearer name for +& than overflow addition.

Scaevolus fucked around with this message at 04:37 on Jun 5, 2014

Toady
Jan 12, 2009

Swift has a subreddit.

Axiem
Oct 19, 2005

I want to leave my mind blank, but I'm terrified of what will happen if I do

Doctor w-rw-rw- posted:

They suggested filing a radar with a concrete suggestion such as the above. (Axiem, get on it)

My colleague apparently got the same answer when he talked with the Apple technicians. Filing the radar is on my to-do list.

An alternate solution would be, I suppose, for Apple to provide a mocking framework, but I don't think we'd see that until next WWDC at the earliest.

Although, a couple of my colleagues and I have been talking about mocks and such, and it's possible that Swift is functional (technically speaking) enough that we can avoid dealing with mocks altogether, and focus more on the whole Functional Core, Imperative Shell thing. I'm going to have to fiddle with it some more to see what I can come up with.

But I'll still file a radar for reflection/proxies, though if Apple either gives us a safe mocking framework or we can do TDD with FCIS, it's a bit more moot to me. Reflection allows for some crazy dangerous stuff, and I can see why Apple would want to avoid that.



rjmccall, what do you make of this article on benchmarking Swift vs. Obj-C?



Also, thanks, Hughlander, for putting the goonlunch together!

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
Okay, I've managed to get my build issues sorted out and I have converted one class in my app to Swift.

It's a simple class, just a Core Data NSManagedObject subclass with a couple of properties and a convenience initializer.

Here's the whole class:
code:
class Sphere : NSManagedObject
{
    @NSManaged var title: String
    @NSManaged var quests: NSSet
    
    class func insertWithTitle(title:String, intoContext context:NSManagedObjectContext) -> Sphere
    {
        let sphere = NSEntityDescription.insertNewObjectForEntityForName("Sphere", inManagedObjectContext:context) as Sphere
        sphere.title = title
        return sphere
    }
}
But I can't appear to cast the return value from insertNewObjectForEntityForName to this class. I assigned it to AnyObject and the type isn't quite the same name.

I can work around it for now by just creating the object outside of the class, but I kind of like being able to construct a Core Data object by just passing some parameters and the context.

Should I file a radar?

WORLDS BEST BABY
Aug 26, 2006

I wanted to see how feasible it was to use Swift in an app I'm working on, so I rewrote a small set of classes and put it up on Github: https://github.com/sgwilym/TableViewIconIndex I'm not a brilliant programmer by any means, but I'd like to use Swift as an opportunity to improve my code — any un-Swiftlike you smart folks can spot in there?

Like a few of the other posters it took a little bit of wrangling to get the Swift compiler to cooperate, as the way Xcode builds the ProductName-Swift.h header file isn't very transparent and requires a little massaging (for one class, I found the only way to get the header file to compile was to change one Character property to the String type). Pretty satisfying to see it working among all the Obj-C classes in the simulator.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Our optimizer isn't where we want it to be yet; there are abstractions being inserted by the standard library that we aren't good enough at removing.

Also, integer arithmetic not matching C performance is not surprising, because we do overflow checking.

But the fact that the post started off by comparing unoptimized builds, and even now is comparing Swift (which uses ARC) against what seems to be manual refcounting, is not inspiring.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Dessert Rose posted:

But I can't appear to cast the return value from insertNewObjectForEntityForName to this class. I assigned it to AnyObject and the type isn't quite the same name.

I can work around it for now by just creating the object outside of the class, but I kind of like being able to construct a Core Data object by just passing some parameters and the context.

Should I file a radar?

Yes, please do. This is probably a matter of us getting somehow confused by the dynamic subclassing that Core Data does.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Scaevolus posted:

What happens when you cause an overflow with normal arithmetic, though? It specifies that it's trapped and reported as an error, but is there any way for a user to handle that?

By design, no. We want to eventually provide a high-level last-resort recovery mechanism, but we don't want a model where programmers can retroactively catch and recover from individual programming-error faults like this. Among other things, it precludes having a "disable the checks" compilation mode, because that would change semantics.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

rjmccall posted:

Yes, please do. This is probably a matter of us getting somehow confused by the dynamic subclassing that Core Data does.

Thought as much :) rdar://17177849

Doctor w-rw-rw-
Jun 24, 2008
I cannot for the life of me figure out the right incantations to map the ObjC block params to the swift closure 'in' thingies:

Objective-C code:
@property(copy) void (^readabilityHandler)( NSFileHandle *)
Swift code:
let fileHandle = NSFileHandle(fileDescriptor: STDIN_FILENO)
fileHandle.readabilityHandler() {
}
Help?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
I don't get why you're trying to call readabilityHandler with a closure. Do you mean
code:
fileHandle.readabilityHandler = { fh in ... }
?

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
The in keyword is just bizarre. Makes no sense to me whatsoever.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
I'm guessing it's from ML where let x = 5 in ...stuff with x... is how variables are declared.

Doctor w-rw-rw-
Jun 24, 2008

Plorkyeran posted:

I don't get why you're trying to call readabilityHandler with a closure. Do you mean
code:
fileHandle.readabilityHandler = { fh in ... }
?

Yes. I am dumb.

Glimm
Jul 27, 2005

Time is only gonna pass you by

I'm a bit confused with the Swift closure syntax myself.

For example, when Xcode autocompletes ReactiveCocoa's RACSignal.createSignal it generates:

code:
RACSignal.createSignal(didSubscribe: ((RACSubscriber!) -> RACDisposable!)?)
I'm sure I'm missing something, but I don't know what to do with that, this works though:

code:
RACSignal.createSignal({(RACSubscriber) -> RACDisposable in
       	return RACDisposable(block: {
	})
})
The ObjC definition of createSignal is:

code:
+ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe;
Is this just weirdness in the autocompletion, or am I missing how to use the autocompleted code somehow?

Axiem
Oct 19, 2005

I want to leave my mind blank, but I'm terrified of what will happen if I do
Good talk, rjmmcall. Kinda sad that it ran over time, though, since I and my colleague were really interested in the Swift internals you were talking about. There should be a fourth talk for Advanced Advanced Swift :v:

rjmccall posted:

But the fact that the post started off by comparing unoptimized builds, and even now is comparing Swift (which uses ARC) against what seems to be manual refcounting, is not inspiring.

I kind of figured as such. Their steadfast opposition to ARC because ~optimization~ doesn't ring well to my ears.

Axiem fucked around with this message at 20:47 on Jun 5, 2014

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

Plorkyeran posted:

I'm guessing it's from ML where let x = 5 in ...stuff with x... is how variables are declared.

That makes sense.

I'm still confused about it, just not in Swift :)

Hughlander
May 11, 2005

Axiem posted:

Good talk, rjmmcall. Kinda sad that it ran over time, though, since I and my colleague were really interested in the Swift internals you were talking about. There should be a fourth talk for Advanced Advanced swift.

For those who missed it rjmcall got played off the stage like an Oscar winner going over time. I hope the full slides are made available and maybe they let you loop audio to finish it.

leedo
Nov 28, 2000

Why am I so excited that map was added? :D Any reason other niceties like reduce and filter weren't also added? (or maybe they were, I just didn't see any mention in the book)

edit: ok got around to installing Xcode 6 beta and reduce and filter appear to exist, neat!

leedo fucked around with this message at 22:42 on Jun 5, 2014

Toady
Jan 12, 2009

Hughlander posted:

I hope the full slides are made available and maybe they let you loop audio to finish it.

I'd expect the full presentation to go up, but finishing the audio would also be nice. Maybe we should contact the dev tools evangelist to request this (delong@apple.com).

Axiem
Oct 19, 2005

I want to leave my mind blank, but I'm terrified of what will happen if I do
One thing I seem to recall hearing in one of the Swift talks this week is that objects in Swift don't have a root class (like objects in Obj-C have NSObject, or Java has Object, etc.). Is that actually the case? If so, why design the language that way?

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Axiem posted:

I kind of figured as such. Their steadfast opposition to ARC because ~optimization~ doesn't ring well to my ears.

That's how I felt on reading that page. Yeah, of course it's not as fast as C. It isn't that much slower than C, and you've got to trade something for those nice features.

"We like manual memory management" indeed. Fine, live in your filth then. I'll be up here in my ivory tower getting poo poo done.

And it's not like performance won't improve over time. ObjC has 20 years of optimization efforts behind it. In five years Swift is going to be a lot faster.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
I've read through the section on two-phase initialization and I'm wondering, what is the reason for requiring that non-nullable ivars be initialized before super.init instead of merely by the end of the initializer body?

The only reason I can think of to do this is to allow for the case where a superclass calls a method that might be overridden in a subclass and thus ensure that those ivars have been set, but that usually screams fragile OO design to me. (Unless I only think that because it's what I've been used to my whole life.)

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
I've wanted to write this code for a very long time :swoon:

code:
@infix func >= (left:NSDecimalNumber, right:NSDecimalNumber) -> Bool
{
    return left.compare(right) != NSComparisonResult.OrderedAscending
}
e: https://gist.github.com/anisoptera/5708afc32454ed868363

Dessert Rose fucked around with this message at 07:00 on Jun 6, 2014

Axiem
Oct 19, 2005

I want to leave my mind blank, but I'm terrified of what will happen if I do

Flobbster posted:

I've read through the section on two-phase initialization and I'm wondering, what is the reason for requiring that non-nullable ivars be initialized before super.init instead of merely by the end of the initializer body?

This gets discussed in I believe the...Intermediate? Swift session (it's all a little blurry to me). Basically, though, when you call super.init(), there's a baked-in assertion in that super.init() that all properties that are not-optional have values (probably at the end of super.init(), if I had to guess, so that it can error out and prevent you from running with nil non-optionals.

rjmmcall, I also meant to give you grief for hating on Ada in the Advanced Swift talk. Ada was the language my college used in CS 101, so I have a bit of a fondness for it. And really, with its extreme type safety, it works better than C in embedded systems, apparently.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Advanced Swift video is up.

Was this the first time that Dave Abrahams' involvement was revealed? There was a lot of speculation about what project Apple had to offer that was interesting enough for him to shut down BoostPro, and I suppose that the chance to work on making generic programming possible in a language while avoiding the problems C++ ran into could certainly qualify.

Axiem
Oct 19, 2005

I want to leave my mind blank, but I'm terrified of what will happen if I do
Oh, and I think I heard an Apple Engineer today slip up and use the code name for Swift instead of Swift. Those in Apple: any idea if it is actually a Firefly reference? (Or is it just as likely to have been the wrong word, but not the codename)

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Axiem posted:

Oh, and I think I heard an Apple Engineer today slip up and use the code name for Swift instead of Swift. Those in Apple: any idea if it is actually a Firefly reference? (Or is it just as likely to have been the wrong word, but not the codename)

It is a Firefly reference.

Also I feel very slightly bad for randomly making fun of Ada. Only very slightly, though.

  • Locked thread