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
Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Ender.uNF posted:

The book calls out that Swift does not do any automatic conversion, you must explicitly do it. It's under "The Basics", "Integer and Floating-Point Conversion":

Doh. Should have searched for "conversion" instead of "coercion". Thanks for pointing that out!

Adbot
ADBOT LOVES YOU

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
rdar://17217571

The following code works in a playground, but segfaults the compiler in an actual iOS app:

code:
import Foundation
import UIKit

class Foo : UIViewController
{
    let foo: (Int) -> String =
    {
        let bar = "xyzzy"
        
        return {(Int) -> String in bar }
    }()
}
It has to be a closure that takes a value and returns a value, and it has to be a UIViewController subclass.

edit: This, however, does work, and is almost as awesome:

code:
    let formatter: NSNumberFormatter =
    {
        let formatter = NSNumberFormatter()
        formatter.positiveFormat = "00"
        
        return formatter
    }()

Dessert Rose fucked around with this message at 21:46 on Jun 7, 2014

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

quote:

doIt("yes")

func doIt(a:String) {

}

error: Use of unresolved identifier 'doIt'


So the compiler isn't smart enough to resolve symbols declared in the same file unless declared in-order?

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Ender.uNF posted:

error: Use of unresolved identifier 'doIt'


So the compiler isn't smart enough to resolve symbols declared in the same file unless declared in-order?

It works in classes, but maybe not at the top level, in a playground which is evaluating line-by-line.

Am I supposed to be able to modify enum values if I pattern-match them?

This:

code:
enum Foo
{
    case Bar(Int)
}

var baz = Foo.Bar(42)

func update(f: Foo)
{
    switch (f)
    {
    case var .Bar(val):
        val -= 1
    }
}

update(baz)
update(baz)
leaves baz's actual value as 42, though I'm allowed to change it within the scope of that function.

It doesn't seem very useful to be able to declare these as mutable if my changes don't affect the underlying object's values.

Dessert Rose fucked around with this message at 04:31 on Jun 8, 2014

Meat Street
Oct 17, 2004

knowin' nothin' in life but to be legit
Sanity check before I file a radar:

code:
func fibonacci(n: Int) -> Int {
    func fibonacciStep(a: Int, b: Int, n: Int) -> Int {
        if (n > 0) {
            return fibonacciStep(b, a+b, n-1)
        } else {
            return a
        }
    }

    return fibonacciStep(0, 1, n)
}
This should be perfectly legal, right? It crashes Xcode every time as written above, but if I don't nest the functions it works just fine.

e: finally got it to spit out an error instead of crashing:

code:
Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x1).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
* thread #1: tid = 0x4b7f8b, 0x0000000000000001, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1)
  * frame #0: 0x0000000000000001

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Dessert Rose posted:

Am I supposed to be able to modify enum values if I pattern-match them?
Enums are value types, so you're passing a copy each time you call update. You have to box the enum if you want to pass a reference.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Plorkyeran posted:

Enums are value types, so you're passing a copy each time you call update. You have to box the enum if you want to pass a reference.

Okay, but this has the same result:

code:
enum Foo
{
    case Bar(Int)
}

var baz = Foo.Bar(42)
switch (baz)
{
case var .Bar(val):
    val -= 1
}
switch (baz)
{
case var .Bar(val):
    val -= 1
}

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
Here, have some exception handling in Swift:

code:
    
try {
        ({
            println("in try")
            //code that might throw an exception
        },
        catch:{ ex in
            println("caught \(ex.name): \(ex.description)")
        },
        finally: {
            println("finally")
        }
    )}
My blog post with the rest of the code. I'm working on getting this packed into a framework and uploaded to GitHub. My next project is LINQ-style operations on SequenceOf<T>. I already have some basics working but I think I can abuse Tuples-as-anonymous-types to support select projections, joining, and grouping.

edit: my rationale is that CoreData already uses exceptions so if you want to interoperate you need to be able to deal with them.

Simulated fucked around with this message at 05:19 on Jun 8, 2014

shodanjr_gr
Nov 20, 2007

This is an exception-al (:haw:) writeup. Thank you.

If I'm reading this correctly, this will also handle nested try calls with rethrowing, correct?

Also, does Swift allow C-style typedefs? Those try function signatures look like brainfuck at first glance.

ultramiraculous
Nov 12, 2003

"No..."
Grimey Drawer

Meat Street posted:

Sanity check before I file a radar:

code:
func fibonacci(n: Int) -> Int {
    func fibonacciStep(a: Int, b: Int, n: Int) -> Int {
        if (n > 0) {
            return fibonacciStep(b, a+b, n-1)
        } else {
            return a
        }
    }

    return fibonacciStep(0, 1, n)
}
This should be perfectly legal, right? It crashes Xcode every time as written above, but if I don't nest the functions it works just fine.

e: finally got it to spit out an error instead of crashing:

code:
Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x1).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
* thread #1: tid = 0x4b7f8b, 0x0000000000000001, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1)
  * frame #0: 0x0000000000000001

I ran into the same thing and rjmccall said it was a bug. I'd file another radar for it, if you have the time.

Meat Street
Oct 17, 2004

knowin' nothin' in life but to be legit

Ender.uNF posted:

edit: my rationale is that CoreData already uses exceptions so if you want to interoperate you need to be able to deal with them.

It was a design decision of the language to not have exceptions and I doubt they'll double back on that, nor would I use them if they were added, but this does raise (heh) an interesting question: does the Core Data talk this year have anything to say about usage patterns in Swift?

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

Meat Street posted:

It was a design decision of the language to not have exceptions and I doubt they'll double back on that, nor would I use them if they were added, but this does raise (heh) an interesting question: does the Core Data talk this year have anything to say about usage patterns in Swift?

All I remember is it saying "it works, use @NSManaged", nothing about exceptions.

lord funk
Feb 16, 2004

Advanced Swift talk was great, rjmccall. It sounded like you guys could have used another session or two to get to everything you wanted to talk about.

toiletbrush
May 17, 2010

Meat Street posted:

It was a design decision of the language to not have exceptions and I doubt they'll double back on that, nor would I use them if they were added, but this does raise (heh) an interesting question: does the Core Data talk this year have anything to say about usage patterns in Swift?
What is a good alternative to exceptions? They're one area of programming I'm very used to using but most of the arguments about them go a bit over my head.

I've kinda given up using Swift for my iOS project (just time constraints) so now I'm facing the usual problem of learning about an awesome new PL and really wanting to try it but having no idea what to actually do with it, so I'm burning through a few Project Euler problems in the Playground, and its a joy. Even the numerous problems that are basically variations on 'how many different ways are there to do xyz' are fun because Swift makes writing your own little expressive DSLs and abstractions so easy.

lord funk
Feb 16, 2004

May be a dumb question, but is there a possibility of an Xcode Edit >> Refactor >> Convert to Swift... in the future?

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

shodanjr_gr posted:

This is an exception-al (:haw:) writeup. Thank you.

If I'm reading this correctly, this will also handle nested try calls with rethrowing, correct?

Also, does Swift allow C-style typedefs? Those try function signatures look like brainfuck at first glance.

You can re-throw; I didn't show the code for throwing an existing NSException but it is trivial.

Your question did set me off on the path to see if I could make actual @throw; work so the existing exception could just be re-thrown, by wrapping @throw in a block created in the @catch, then using a Block** parameter to write its address back out to the Swift side; this would defer creating the block unless you actually cared about rethrowing. I almost got there but I no matter what I did the AutoreleasingUnsafePointer<Block?> out param was always nil on the Swift side. I switched to always creating the rethrow block instead of trying to do it lazily and it actually works. However it creates an ambiguity in the catch clause definitions, so you end up having to clutter the catch with "(ex, rethrow) -> () in" for little benefit.


Meat Street posted:

It was a design decision of the language to not have exceptions and I doubt they'll double back on that, nor would I use them if they were added, but this does raise (heh) an interesting question: does the Core Data talk this year have anything to say about usage patterns in Swift?

I am not advocating for exceptions, just dealing with the fact that they exist and will be thrown if you're using CoreData.

I still think we need something more robust than "func() -> (x:T, error:NSError)" or "func (x:T, inout error:NSError)", but I am starting to think I'm in the minority. In my far future dream world, failure to account for integer overflow doesn't cause a kernel panic because the serial driver for my home automation transmitter got a bad packet. Yes, that would be a bug. Yes, it should be handled or fixed. But in the meantime, I'd like my software to be robust and resilient. Now that we aren't stomping all over memory willy-nilly, we can reason far more effectively about the state of a program in the face of an unexpected error. Hopefully someone smarter than me is thinking about this stuff.



lord funk posted:

May be a dumb question, but is there a possibility of an Xcode Edit >> Refactor >> Convert to Swift... in the future?

My guess is no. Although you could parse the straightforward Objective-C code and do some conversions, my guess is there is enough C and ambiguity in there to effectively make it impossible for anything but trivial Objective-C classes, in which case why bother?

Closest things I can think of are automatic VB<->C# compilers which have some similarities because both of those are using the same runtime/framework, similar to Swift and Objective-C. However in that case you have a much more well-defined surface area to deal with (far fewer undefined behaviors), they have a mostly unified type system (something Swift and ObjC do not share), and full metadata.... and it still produces butt-ugly un-maintainable code.

But I could be very wrong about this so YMMV.

Simulated fucked around with this message at 19:44 on Jun 8, 2014

lord funk
Feb 16, 2004

I got excited after seeing all the cool projection of Swift -> ObjC / ObjC -> Swift stuff. I figure if that much work is already done, it might not be too far of a leap to just translate an implementation completely.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

toiletbrush posted:

What is a good alternative to exceptions? They're one area of programming I'm very used to using but most of the arguments about them go a bit over my head.

Conditions sound pretty cool, though I have no actual coding experience with them so I don't know how they hold up in practice. Basically they're like exceptions but you don't have to handle the exception where you catch it. So you don't have to unwind the (whole) stack, though you can if you want.

To my eyes it's vaguely reminiscent of the design of NSProgress, in that you can monitor and affect lower-level functions without directly mucking about. I'm pretty sure you could implement NSProgress on top of conditions.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Dessert Rose posted:

Okay, but this has the same result:

code:

enum Foo
{
    case Bar(Int)
}

var baz = Foo.Bar(42)
switch (baz)
{
case var .Bar(val):
    val -= 1
}
switch (baz)
{
case var .Bar(val):
    val -= 1
}

val is just a copy of the value stored there; there is no way to update in-place like this, and that's by design.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Ender.uNF posted:

error: Use of unresolved identifier 'doIt'

So the compiler isn't smart enough to resolve symbols declared in the same file unless declared in-order?

There are secretly two kinds of swift file: scripts and everything else. Scripts are evaluated line-by-line, which (for various reasons) means that it's not reasonable for lookup to find things declared later. In a non-script, you can't have expressions at the top-level, global variables are initialized lazily, and everything is allowed to refer to everything. Playgrounds and the REPL are processed as scripts.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Ender.uNF posted:

Here, have some exception handling in Swift:

This is really cool.

Meat Street posted:

It was a design decision of the language to not have exceptions and I doubt they'll double back on that

I wouldn't go that far. I'd say that we aren't very happy with the EH designs of current languages and want some more time to evaluate our options without committing to something half-assed.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

shodanjr_gr posted:

Also, does Swift allow C-style typedefs? Those try function signatures look like brainfuck at first glance.

That's what typealias is. (Except in a protocol body.)

Gul Banana
Nov 28, 2003

speaking of which, is typealias-in-protocol semantically equivalent to a hypothetical Protocol<T>? that is, does it have any special features or restrictions that generic protocols wouldn't, if they existed?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
It makes the associated type functionally dependent on the principal type. With Sequence<T>, it is theoretically sensible for a type to conform to both Sequence<Int> and Sequence<Float>. That's rarely useful, and it makes the type system far more complicated.

That's not to say that we couldn't do something like that as sugar, though.

Meat Street
Oct 17, 2004

knowin' nothin' in life but to be legit
rjmccall (or anyone else), I'm curious: do you have any recommendations as far as getting up to speed on the more functional side of things? Obviously it doesn't have to be Swift-specific. Last time I tried Learn You A Haskell it flew over my head, but maybe I should give it another shot now that I have some more concrete motivation :)

Toady
Jan 12, 2009

Implementation of Lisp cond in Swift. Demonstrates @auto_closure.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Ahaha best ending to a session. Nicely done!

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
It was crazier during the actual talk, because I actually sprinted through the remaining half-dozen slides, rushing all the content while the staff turned on the music and raised the house lights. We debated what to do for the recording, and I told them to cut there because (1) it is hilariously abrupt and (2) the next fifteen seconds were basically just me stuttering out gibberish anyway while I slowly realized what was happening.

Meat Street, I don't have specific suggestions about learning functional programming, sorry.

ultramiraculous
Nov 12, 2003

"No..."
Grimey Drawer

Meat Street posted:

rjmccall (or anyone else), I'm curious: do you have any recommendations as far as getting up to speed on the more functional side of things? Obviously it doesn't have to be Swift-specific. Last time I tried Learn You A Haskell it flew over my head, but maybe I should give it another shot now that I have some more concrete motivation :)

The Coursera course on Scala is a pretty good starting point if you really want to get broken down and start looking at things functionally.

Hughlander
May 11, 2005

rjmccall posted:

It was crazier during the actual talk, because I actually sprinted through the remaining half-dozen slides, rushing all the content while the staff turned on the music and raised the house lights. We debated what to do for the recording, and I told them to cut there because (1) it is hilariously abrupt and (2) the next fifteen seconds were basically just me stuttering out gibberish anyway while I slowly realized what was happening.

Meat Street, I don't have specific suggestions about learning functional programming, sorry.

Who's the evangelist? I want to send in E-Mail asking that you go back and loop over the slides / remaining slides and give the full presentation as it was designed to be.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Hughlander posted:

Who's the evangelist? I want to send in E-Mail asking that you go back and loop over the slides / remaining slides and give the full presentation as it was designed to be.

The DT evangelist is Dave DeLong. There really isn't much substantive missing content, though:

1. Overflow checking is good.
2. There are masking operators which skip overflow checks when you want that, like if you're writing a hash function.
3. You can pass -Ofast to turn off safety checks file-by-file when you're certain that's a good idea.
4. Let's recap what we talked about today.
5. Thanks for coming and have a great WWDC.

lord funk
Feb 16, 2004

Are property observers meant to substitute for key value observation in ObjC? It seems to me that they're very local, like having a class observe itself, but not able to be used for MVC coordination the way I've been using KVO.

Toady
Jan 12, 2009

lord funk posted:

Are property observers meant to substitute for key value observation in ObjC? It seems to me that they're very local, like having a class observe itself, but not able to be used for MVC coordination the way I've been using KVO.

As of now, you have to rely on NSObject's implementation for that kind of KVO.

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?

Ender.uNF posted:

I am not advocating for exceptions, just dealing with the fact that they exist and will be thrown if you're using CoreData.

Core Data really shouldn't be throwing an exception for anything that isn't programmer error; if it is, report it as a bug and send me the bug number for followup if you can.

Doctor w-rw-rw-
Jun 24, 2008

eschaton posted:

Core Data really shouldn't be throwing an exception for anything that isn't programmer error; if it is, report it as a bug and send me the bug number for followup if you can.

If programmer error will happen, then it follows that exceptions will happen. I think it was implicit in his statement that if you're using Core Data, you're probably going to misuse it at some point and trigger an exception.

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?

Doctor w-rw-rw- posted:

If programmer error will happen, then it follows that exceptions will happen. I think it was implicit in his statement that if you're using Core Data, you're probably going to misuse it at some point and trigger an exception.

I mean programmer error in the Cocoa sense; Cocoa exceptions aren't meant to be caught by an app and recovered from, they're meant to be caught by a debugger and prevented.

In other words, "Core Data throws this exception I can't catch in Swift and there's nothing my code can do to prevent it" is properly solved by fixing Core Data not to throw an exception, rather than by letting your app continue with potentially corrupt state.

Of course, if it's because of something an app did (like trying to fire a fault for a deleted object) the solution is to not get into that situation in the first place.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

eschaton posted:

I mean programmer error in the Cocoa sense; Cocoa exceptions aren't meant to be caught by an app and recovered from, they're meant to be caught by a debugger and prevented.

In other words, "Core Data throws this exception I can't catch in Swift and there's nothing my code can do to prevent it" is properly solved by fixing Core Data not to throw an exception, rather than by letting your app continue with potentially corrupt state.

Of course, if it's because of something an app did (like trying to fire a fault for a deleted object) the solution is to not get into that situation in the first place.

A suitably paranoid app might want to catch a Core Data exception, save some state for recovery, then rethrow. While the conscientious developer is typing up their bug report, their customers keep their data.

I'm rarely so paranoid, but it's not outright ridiculous that an app might want to catch an exception from Core Data.

Toady
Jan 12, 2009

I'd be paranoid of writing to disk since Core Data would be in an undefined state.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

Nipplebox posted:

I'd be paranoid of writing to disk since Core Data would be in an undefined state.

Well you wouldn't ask a managed object context to save, but you could poke at any managed objects you have hanging around and stuff a plist somewhere (being sure not to fire faults), or grab the contents of a text view.

This doesn't really have much to do with Swift, though. We can take it to the Apple dev thread.

Adbot
ADBOT LOVES YOU

Toady
Jan 12, 2009

I'd lean on autosave and state restoration, but I'm a lazy hack. I wonder if Swift will end up with some way of working with exceptions for the sake of C++ interoperability.

  • Locked thread