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
ultramiraculous
Nov 12, 2003

"No..."
Grimey Drawer
http://www.jessesquires.com/apples-to-apples-part-two/

drat, ladies. Things are getting Swift!

Adbot
ADBOT LOVES YOU

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

No poo poo it's faster all he's doing is showing that objc_msgSend is a bottleneck

Dump them to (C) arrays and use qsort on the values and/or cache the comparator and it'd be much faster.

That said swift does it by default.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
It's an interesting question. Objective-C embeds C; any sort of benchmark showing Objective-C to be slow can be met with the objection, "Well, if the performance really mattered here, I would just drop down to C." That's a reasonable response inasmuch as it's a real strength of Objective-C that using C techniques in any particular method implementation is so painless. On the other hand, that means you're no longer really comparing against Objective-C, because you're (locally) losing basically everything that Objective-C gives you; it also implies that you're losing a lot of performance in the long tail of places that you will never plausibly get around to hand-optimizing. On the other other hand, that performance buys a lot of dynamic flexibility that this workload could, but does not, take advantage of. Most language benchmarks tell a complex story like this.

For what it's worth, we internally wrote up cute benchmarks like this years ago, but AFAIK we've never bragged about them, mostly because we felt that it requires too much explanation.

On one final note, I want to point out that the performance difference is not really about the direct overhead of objc_msgSend; you could duplicate most of it by just taking every message send and making it a call to a function implemented in a different file. It's about boxing and the abstraction penalty of making an opaque call instead of an inlineable one.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
code:
func takeFive<T:IntegerArithmeticType>(a:T)(b:T)(c:T)(d:T)(e:T) -> T {
    println("{a=\(a), b=\(b), c=\(c), d=\(d), e=\(e)}")
    return a + b + c + d + e
}

let f1 = takeFive(5)
let f2 = f1(b: 4)
let f3 = f2(c: 3)
let f4 = f3(d: 2)
let f5 = f4(e: 1)

let ret = takeFive(5)(b:4)(c:3)(d:2)(e:1) //15

println("\(f5) vs \(ret)")

swiftc posted:

{a=5, b=1, c=1, d=1, e=1}
{a=5, b=4, c=3, d=2, e=1}
9 vs 15

Wat :what:


edit: this works just fine
code:
func takeFive(a:Int)(b:Int)(c:Int)(d:Int)(e:Int) -> Int {
    println("{a=\(a), b=\(b), c=\(c), d=\(d), e=\(e)}")
    return a + b + c + d + e
}
So does doing it manually:

code:
func takeFive<T:IntegerArithmeticType>(a:T) -> (T->(T->(T->(T->T)))) {
    return { (b:T)  in
        return { (c:T) in
            return { (d:T) in
                return { (e:T) in
                    return a + b + c + d + e
                }
            }
        }
    }
}
Also, the docs do not specify that an argument name is required for curried functions but they are. Attempting to specify "_ b" gives a warning that the argument is not named but in either case it requires the caller specify the name.

rdar://17973350 and rdar://17973340

Simulated fucked around with this message at 05:36 on Aug 11, 2014

Kallikrates
Jul 7, 2002
Pro Lurker
Has anyone found a better solution to sharing Swift and Obj-C interop between build Targets?:

Given that Swift -> Obj-C headers are named after the target that generates them of the form: "TargetA-Swift.h"...

And I have Swift and Obj-C files I want to share between targets A and B
Foo.m imports "TargetA-Swift.h" in build TargetA and works fine
I want to import Foo.m into TargetB build does not work fine because "TargetA-Swift.h" does not exist for TargetB
I have created a "Foo-Swift.h" that "Foo.m" can import that conditionally imports either "TargetA-Swift.h" or "TargetB-Swift.h"based on compile time flags.

I think there should be a better way and we should be allowed to rename the Swift -> Obj-C headers that Xcode generates the precedent already exists for renaming the Objc-C -> Swift Header We provide Xcode. Opinions? (rdr: 18063617)

lord funk
Feb 16, 2004

Regarding lazy loading:

In some cases I've found it's nice to allow for recalculation of a property by nilling out its backing store. So in Obj-C:

Objective-C code:
- (NSArray *)someArray
{
    if (!_someArray) {
        //calculate the goods
    }
    return _someArray;
}
That array would be used until some later point where the data might change. You could then nil out _someArray, and redo the lazy loading later. My questions are:

1. Since lazy properties are only calculated once, how could this be done in Swift?
2. Or is this a bad habit of mine and there's a better way?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You just need to make a private optional property backing a property with a getter. The @lazy sugar isn't going to satisfy every imaginable use case.

Toady
Jan 12, 2009

lord funk posted:

Regarding lazy loading:

In some cases I've found it's nice to allow for recalculation of a property by nilling out its backing store. So in Obj-C:

Objective-C code:
- (NSArray *)someArray
{
    if (!_someArray) {
        //calculate the goods
    }
    return _someArray;
}
That array would be used until some later point where the data might change. You could then nil out _someArray, and redo the lazy loading later. My questions are:

1. Since lazy properties are only calculated once, how could this be done in Swift?
2. Or is this a bad habit of mine and there's a better way?

You're describing a cache that stores transient data. Lazy properties just lazily calculate a stored property's initial value, to defer expensive work or make use of information that isn't available when the object is initialized.

PleasureKevin
Jan 2, 2011

two things I could do in PHP that I guess I can't in swift?

1 . omit curly braces if i'm just doing one line below an if statement

2. if statements that create a variable and return false if unsuccessful

so this should not work:

pre:
if (var joke = speaker.TellJoke?())
    println(joke) 
else 
    println("that creature can't tell jokes")
is that right?

eschaton
Mar 7, 2007

Don't you just hate when you wind up in a store with people who are in a socioeconomic class that is pretty obviously about two levels lower than your own?

PleasureKevin posted:

two things I could do in PHP that I guess I can't in swift?

1 . omit curly braces if i'm just doing one line below an if statement

Correct, you can't omit braces, and this is a feature.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
Are there any resources, videos and such for learning swift form a beginners point of view? I have some python skills but want something from the ground up? Is it too early for this?

Its so much easier to read then objC and I don't want to learn that if I can learn swift instead and get ahead of the crowd dev wise.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

PleasureKevin posted:

two things I could do in PHP that I guess I can't in swift?

1 . omit curly braces if i'm just doing one line below an if statement

2. if statements that create a variable and return false if unsuccessful

so this should not work:

Swift code:
if (var joke = speaker.TellJoke?())
    println(joke) 
else 
    println("that creature can't tell jokes")
is that right?

You can write this:

Swift code:
if var joke = speaker.TellJoke?() {
    println(joke)
} else {
    println("that creature can't tell jokes")
}
assuming that TellJoke is, like, an optional protocol method or something. Optional protocol methods are still an incomplete feature in the general case, but the ObjC side of them works.

Requiring curly braces is one of those things that very slightly annoys you until you just get over it. The downside is that it requires some extra vertical whitespace because of the trailing brace. The main upside is that you stop wasting your life janitoring curly braces around one-line substatements that turn multi-line and vice versa; the fact that it resolves elses unambiguously is a nice side-effect.

rjmccall fucked around with this message at 19:59 on Sep 3, 2014

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

thegasman2000 posted:

Are there any resources, videos and such for learning swift form a beginners point of view? I have some python skills but want something from the ground up? Is it too early for this?

Its so much easier to read then objC and I don't want to learn that if I can learn swift instead and get ahead of the crowd dev wise.

I know that a lot of the usual suspects in the ObjC dev community are working on books, courses, etc. One thing you have to be aware of is that Swift is still a moving target: the implementation is still maturing, of course, but much more importantly, we expect to make a number of major changes to the language and libraries over the new few years. So when you're looking for resources, look for things that you feel confident will be regularly updated; in particular, for the love of god, don't buy a physical book.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:

rjmccall posted:

I know that a lot of the usual suspects in the ObjC dev community are working on books, courses, etc. One thing you have to be aware of is that Swift is still a moving target: the implementation is still maturing, of course, but much more importantly, we expect to make a number of major changes to the language and libraries over the new few years. So when you're looking for resources, look for things that you feel confident will be regularly updated; in particular, for the love of god, don't buy a physical book.

Are apple themselves working on a video tutorial series or anything? I like videos, even without boobs!

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

thegasman2000 posted:

Are apple themselves working on a video tutorial series or anything?

I don't specifically know of any planned videos, but I also don't keep track of everything that the docs people are planning. I'm sure that people externally are planning videos, and I know for a fact that we (meaning both Apple generally and the language development team specifically) provide a lot of content guidance/feedback to people in the community.

ultramiraculous
Nov 12, 2003

"No..."
Grimey Drawer
Is there an especially expedient way to report issues with ObjC->Swift header issues before things start getting real next week? I filed rdar://18206277 for some UILabel issues, and I'm wondering where I should file similar issues.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
If you're filing bugs now with the expectation that they'll be fixed in the first official release build, I'm not sure what to tell you.

That said, if you're concerned that bugs that don't get fixed right now will take six months before they show up in a build you can use, then... well, I shouldn't speculate, but I hope you're not disappointed on that front.

feedmegin
Jul 30, 2008

eschaton posted:

Correct, you can't omit braces, and this is a feature.

What a shock that someone at Apple specifically noticed http://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/ and thought mitigating it might be an idea :)

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
We designed it this way two years before that bug came out, but it's certainly a great reminder of why this is the right thing to do. It's also a great cudgel for convincing systems engineers to actually take advantage of the tools we give them.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



rjmccall posted:

We designed it this way two years before that bug came out, but it's certainly a great reminder of why this is the right thing to do. It's also a great cudgel for convincing systems engineers to actually take advantage of the tools we give them.

I am into this, cause every time I write a simple statement like if (a) b() I am tempted to write it like that. Then I rethink it and add the braces, but then I'm like, this is too busy looking plust the braces aren't necessary. Being forced to make the right choice is sometimes a gift, at least if you're a huge idiot like I am.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
I'm writing a keyboard extension in Swift and installed the GM on my phone to try it out. I wiped DerivedData and cleaned everything just to be on the safe side, but now I can't get the extension to start at all. All I see is this in my device logs:

code:
Dyld Error Message:
  Library not loaded: @rpath/libswiftCore.dylib
  Referenced from: /private/var/mobile/Containers/Bundle/Application/D6271BED-A1A3-441B-9EA7-BEEC3A6FFB4C/MyApp.app/PlugIns/MyKeyboard.appex/MyKeyboard
  Reason: image not found
  Dyld Version: 353.5
I noticed something potentially relevant in the release notes:

quote:

Signed OS X App Extensions may emit dyld warnings and fail to launch.
Ensure that the same team ID is set for both the app extension and the containing app. (17711503)

But I've done that and still have the problem. I even get this on a brand new project with just the basic storyboard and keyboard extension generated by default. The only potential oddity I can think of is that the containing app is Obj-C (for historical reasons) and the extension is Swift.

Anyone else run into this and come up with a fix?

EDIT: Upon further inspection, it looks like it's a problem that only manifests for Obj-C container apps with Swift extensions. If I create a new Swift app with a Swift extension, it starts fine. Not sure why this stopped working (it was fine as of Xcode beta 7) or what the cleanest fix (some combination of build settings, hopefully) is.

Flobbster fucked around with this message at 06:36 on Sep 10, 2014

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
What if you put some trivial bit of Swift code in the app?

I've noticed a "copying Swift standard library" compiler step go by during the betas, I wonder if that's not getting triggered for some reason.

duck pond
Sep 13, 2007

Flobbster posted:

I'm writing a keyboard extension in Swift and installed the GM on my phone to try it out.

I'm creating a keyboard extension too (and from your previous posts I suspect we're both building a unicode character picker), but all in ObjC - and when I installed the GM mine wouldn't start either. I'm just gonna create a new project from scratch too, I think.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
pokeyman, it looks like adding a dummy Swift class to my app container did the trick, thanks (I was too tired to try it last night). Feels hacky, but I guess no hackier than fudging the linker settings manually, and this was faster.

duck pond posted:

I'm creating a keyboard extension too (and from your previous posts I suspect we're both building a unicode character picker), but all in ObjC - and when I installed the GM mine wouldn't start either. I'm just gonna create a new project from scratch too, I think.

THE BATTLE IS ON
(good luck with yours!)

What kind of errors are you getting on your end?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You probably just need an empty Swift file in the app; no need to even put a dummy class in it. You basically just need to fool the build system.

Please file that, though!

Also, you'll notice that we also released beta Mavericks Yosemite tools; if you're doing Swift development, I encourage you to use those over the GM iOS tools, even if you're doing iOS development. The GM tools are more stable, but the beta tools have more fixes and language changes in them, and you're probably not literally submitting tomorrow.

ETA: Haha, I know the real names of our operating systems, honest.

rjmccall fucked around with this message at 23:40 on Sep 10, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

rjmccall posted:

ETA: Haha, I know the real names of our operating systems, honest.

"Butthead National Park"

duck pond
Sep 13, 2007

Flobbster posted:

THE BATTLE IS ON
(good luck with yours!)

For the record I'm on holiday in Turkey and working over dodgy hotel WiFi, so I'm doing this on hard mode :unsmigghh:. It's a miracle I was even able to download the GM at all...

Flobbster posted:

What kind of errors are you getting on your end?

The app is starting up fine, but when I run the extension on its own it crashes before the debugger even starts talking to it... Hrm. I'll figure it out.

Also holy moly I regenerated the project and was wondering where the LaunchImage.xcassets was, turns out it's LaunchImage.xib now (!) That's pretty cool.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
It would have been nice to know a few months ago that iTunes was going to be rejecting Swift libraries targeting iOS 7.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Plorkyeran posted:

It would have been nice to know a few months ago that iTunes was going to be rejecting Swift libraries targeting iOS 7.

I'm pretty sure we fully support iOS 7 as a target. Maybe there's a bug in the submission process?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
The error message when submitting is just "Invalid Info.plist value. The value for the key 'MinimumOSVersion' in bundle {framework name} is invalid. The minimum value is 8.0" and it happens only if the framework contains any Swift code. Maybe just a miscommunication somewhere about what was supported? Sideloading the ipa to an iOS 7 device works fine.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Yeah, I don't know what that's about; I'm sure you're not alone in seeing it, but please file it.

PleasureKevin
Jan 2, 2011

I'm following the Ray Wenderlich tutorials and I don't think I understand this passage.

Ray Wenderlich posted:

Finally, select your table view, and select the sixth Inspector (the Connections Inspector). You’ll see two entries for dataSource and delegate – drag the buttons to the right of those over to your view controller in the Document Outline.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

PleasureKevin posted:

I'm following the Ray Wenderlich tutorials and I don't think I understand this passage.

This is more an Apple programming question than a Swift one, but I think he means to connect those outlets to your controller (which, in real terms, means setting properties of the source object to point to the instance of your controller class that will get dynamically created during NIB loading), which you do by control-dragging from one to the other.

Glimm
Jul 27, 2005

Time is only gonna pass you by

Is this a Swift issue or something I'm doing wrong?

code:
let error = NSError()
println("error domain: \(error.domain)") // EXC_BAD_ACCESS

This fails to compile entirely as domain is not an optional:

code:
        if let domain = error.domain {

        }
I think one shouldn't be making NSError's without a domain and code (the NSError that brought this to my attention is from someone elses test case), but the fact that it is possible makes me think I should be able to handle it gracefully. Am I missing something simple here?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Glimm posted:

I think one shouldn't be making NSError's without a domain and code (the NSError that brought this to my attention is from someone elses test case), but the fact that it is possible makes me think I should be able to handle it gracefully. Am I missing something simple here?

This seems like an SDK issue. When Swift imports an ObjC class, it gets all the initializers declared anywhere in its class hierarchy. This is the right default, because it's quite common for ObjC classes to inherit initializer signatures from their superclasses without explicitly redeclaring them in their @interfaces. In some cases, however, this is problematic, because the class's invariants require it to be initialized in a certain, subclass-specific way. That's what's happening here, and the right fix is probably for NSError to redeclare -init and mark it unavailable.

In the meantime, yeah, you just need to be careful to not create NSErrors that way.

Glimm
Jul 27, 2005

Time is only gonna pass you by

rjmccall posted:

This seems like an SDK issue. When Swift imports an ObjC class, it gets all the initializers declared anywhere in its class hierarchy. This is the right default, because it's quite common for ObjC classes to inherit initializer signatures from their superclasses without explicitly redeclaring them in their @interfaces. In some cases, however, this is problematic, because the class's invariants require it to be initialized in a certain, subclass-specific way. That's what's happening here, and the right fix is probably for NSError to redeclare -init and mark it unavailable.

In the meantime, yeah, you just need to be careful to not create NSErrors that way.

OK, good to know - thanks!

brap
Aug 23, 2004

Grimey Drawer
I just got the Xcode 6 public release. I can't make new Cocoa applications with Swift as the language-- only iOS applications. I have googled around a bit and not gotten much. What gives?

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

fleshweasel posted:

I just got the Xcode 6 public release. I can't make new Cocoa applications with Swift as the language-- only iOS applications. I have googled around a bit and not gotten much. What gives?

OS X gains Swift in Xcode 6.1, which is currently in beta (accessible to paid-up iOS devs and OS X devs). Presumably that'll get a public release alongside Yosemite.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Yep. Swift's C/ObjC importer relies in some places on the exact contents of the SDK, and there were changes made to support us in the Yosemite SDK that were not backported to the Mavericks SDK. With such a small gap between releases, we felt that it was better to concentrate on providing a good experience on a single reliable SDK than to try to support a less-vetted SDK for a month.

You can, of course, still target a minimum deployment version of Mavericks while using the Yosemite SDK.

Adbot
ADBOT LOVES YOU

Volte
Oct 4, 2004

woosh woosh
So what's the deal with Swift's weird generic limitations? I'm trying to define a simple (imperative) expression-tree type of class hierarchy. I already can't use algebraic datatypes because I can't do something like:
code:
enum Expr<T> {
  case Const(T)
  case Var(Variable<T>)
  case BinOp<U, V>(Op<U, V, T>) // can't introduce U,V
  // ...
}
(actually, enums with generics in their payloads seem to cause the compiler to segfault anyway) so instead I have an Expr<T> base class and I have like BinOp<U, V, T>: Expr<T>. The weirdness comes in when defining If statements. In any other language I'd do this:
code:
class IfStatement: Expr<Void> {
    var condition: Expr<Bool>
    var expr: Expr<Any>
    
    init(condition: Expr<Bool>, expr: Expr<Any>) {
        self.condition = condition
        self.expr = expr
    }
}
But in Swift for some reason a class derived from a generic must also be generic. So at first I thought this made Swift generics all but useless for type hierarchies, but then it turns out I can do this (I think, I have compiled but not actually tested it):
code:
class IfStatementImpl<Void>: Expr<Void> {
    var condition: Expr<Bool>
    var expr: Expr<Any>
    
    init(condition: Expr<Bool>, expr: Expr<Any>) {
        self.condition = condition
        self.expr = expr
    }
}
typealias IfStatement = IfStatementImpl<Void>
This seems like a weird limitation that doesn't need to exist (especially if it can be worked around with this trick) and the concept of creating a generic class with no type arguments does not make a single bit of sense to me. I haven't really found anything about this other than people complaining about it, so does anyone know why this is the case or if it will be changed in the future?

Volte fucked around with this message at 13:34 on Sep 20, 2014

  • Locked thread