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
Volte
Oct 4, 2004

woosh woosh

Dessert Rose posted:

C# does not have that "feature". It's a compile error if the same name could refer to two different things in the same scope.
It can't shadow things at control statement scope but it and every other language I've used you can shadow variables at the function scope.
code:
public class Test {
  int i;	
  public static void Main() {
    int i = 4;
    // ...     
  }
}
Sorry for being unclear about which feature I meant.

edit: I guess that's not exactly the same since you can still refer to this.x.

Volte fucked around with this message at 11:31 on Oct 6, 2014

Adbot
ADBOT LOVES YOU

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Volte posted:

It can't shadow things at control statement scope but it and every other language I've used you can shadow variables at the function scope.
code:
public class Test {
  int i;	
  public static void Main() {
    int i = 4;
    // ...     
  }
}
Sorry for being unclear about which feature I meant.

edit: I guess that's not exactly the same since you can still refer to this.x.

That works but this doesn't:

code:
public class A
{
public int i = 5;
public void M()
{
i = 3;
int i = 7;
Console.WriteLine("{0}", i);
}
}

code:
Cannot use local variable 'i' before it is declared. The declaration of the local variable hides the field 'A.i'.

(Forgive awful indentation)

There's a special case if the same name never actually refers to a different variable in the same scope. (Or I suppose you could see it as a special case if you engineer a situation where it does.) See http://ericlippert.com/2009/11/02/simple-names-are-not-so-simple/ for a good explanation of these rules in C#.

The original code, where the same name is declared multiple times as having a different type, would not compile in C# unless you used a separate name for the cast type every time inside its own scope, like using "o" for the original object and "j" for the target of your cast.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
rjmccall: I just now realized that your team removed @conversion/__conversion.

There is not enough room to describe my hate at this moment.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I'm not sure what about having to type "__conversion" gave you the impression that it was seriously supported. :shobon:

It's possible that we'll add a user-defined conversion feature back at some point, but we're feeling pretty burnt by it right now. Too many unexpected results, and too terrible an impact on compile time, which is already a seriously sore spot.

Can you concisely express what you'd like to do?

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
Basically create a transparent wrapper that can degrade to the wrapped type without having to refactor a bunch of code with useless glue. (It was @conversion that made me think it might be a legit feature.) It's not really hate, I was just getting frustrated trying to write a new class in Swift and call it from Objective-C, I kept running into issues like defining enums in Swift, etc.



I also just ran into a case where I greatly miss the ability to say "yes, yes compiler... I know this isn't technically safe, but trust me, class X totally has private members with definition A,B,C so please let me break the rules". The Alamofire library implements didReceiveChallenge and does its own SSL verification. It does not expose the delegates, nor any way to handle that. I am connecting to a system using a self-generated certificate that I know how to validate, but there is no way for me to do so. This is just an example, it could be any situation.

If this were Objective-C, I would just declare my own header for the private delegate class and/or swizzle the method and make it work, without having to maintain my own fork of Alamofire (or worse, not having the source).

If this were C#, I would use runtime IL generation (or the newer Expression<T> stufF) to create a dynamic method and patch it in, or possibly use reflection to grab and set private fields.

Are both of those things hacks? Certainly. Are they absolutely necessary at times, including to work around bugs in system frameworks? Yup. I know that I can assume @objc objects derived from NSObject are usable with the standard Objective-C runtime calls, I just wish Swift had a native way to do it. It can be a pain with big fat "warning: at your own risk" on it, but it should exist. (think "unsafe{}" blocks in C#, which IIRC the default csproj disables so you have to explicitly take responsibility for it)



While I'm complaining, is there not a syntax to combine boolean logic and optional unwrapping in one if statement, or even multiple optional unwraps?

code:
if let x = maybeX, y = maybeY, var z = maybeZ { }

if let x = maybeX && butts > farts { }
I also find myself desperately wanting a concise way to express "if this optional is non-nil, then see if it responds to selector/defines method X, if so call it, else pretend the whole thing was nil". Instead I'm doing:

code:
if let obj = notification?.object { 
    if obj.respondsToSelector(Selector("hey")) {
    }
}
I would file radars but I already have a queue of 20 to go verify as fixed and still haven't unpacked everything.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Can you express that method check using an optional method somehow? If so, it should be as concise as:

Swift code:
notification?.object.hey?()

I'll try to unpack/forward the rest of this later.

Kallikrates
Jul 7, 2002
Pro Lurker

Ender.uNF posted:


While I'm complaining, is there not a syntax to combine boolean logic and optional unwrapping in one if statement, or even multiple optional unwraps?

code:
if let x = maybeX, y = maybeY, var z = maybeZ { }

if let x = maybeX && butts > farts { }
I also find myself desperately wanting a concise way to express "if this optional is non-nil, then see if it responds to selector/defines method X, if so call it, else pretend the whole thing was nil". Instead I'm doing:

code:
if let obj = notification?.object { 
    if obj.respondsToSelector(Selector("hey")) {
    }
}
I would file radars but I already have a queue of 20 to go verify as fixed and still haven't unpacked everything.

On one hand if let is cool on the other if I care about other conditions, I end up deeply nested structures in code or lots of tiny functions, this would improve my QoL greatly.

Toady
Jan 12, 2009

quote:

This Thanksgiving when you sit down for dinner thankful for the increase in Apple stock option value, remember all the little developers you have trampled on with this arrogance.

Sometimes the developer forums make me smile.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
A little heads up to anyone wanting some swift specific tutorial action. Lynda have a course http://www.lynda.com/Swift-tutorials/Swift-Essential-Training/180105-2.html

Through this I just realised how much I like the range function in switch statements :)

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

rjmccall posted:

Can you express that method check using an optional method somehow? If so, it should be as concise as:

Swift code:
notification?.object.hey?()
I'll try to unpack/forward the rest of this later.

No, I don't think so. It throws doesNotRecognizeSelector if object doesn't implement hey. I'll double check tonight though.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
code:
// Playground - noun: a place where people can play

import UIKit
import XCPlayground

XCPSetExecutionShouldContinueIndefinitely()

let kMyNotification = "Butts"

@objc class Wat : NSObject, WatProtocol {
}

@objc protocol WatProtocol : NSObjectProtocol {
    optional func lolers()
}

NSNotificationCenter.defaultCenter().addObserverForName(kMyNotification, object: nil, queue: nil) {
    (notification) -> Void in
    //ERROR: AnyObject does not have a member named 'lolers()'
    //println("Wat = \(notification.object?.lolers?())")

    if let oops = notification.object as? WatProtocol {
        //Prints Wat = nil, yay!
        println("Wat = \(oops.lolers?())")
    }
}

let myObj = Wat()
NSNotificationCenter.defaultCenter().postNotificationName(kMyNotification, object: myObj)
Indeed, you cannot use optional method chaining except with protocol optional methods, which makes it fairly useless (or requires a ton of boilerplate extensions).

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Huh. It should definitely be letting you ask for that method with AnyObject-based dispatch. That's a bug.

As a workaround, try just throwing @objc on the implementations of that method that you're hoping to find.

Doctor w-rw-rw-
Jun 24, 2008
Apologies if this has already been covered, but the docs appear incorrect:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

Using Swift with Cocoa and Objective-C, Working with Cocoa Data Types posted:

Swift bridges NSUInteger and NSInteger to Int. Both of these types come over as Int in Foundation APIs. Int is used for consistency whenever possible in Swift, but the UInt type is available if you require an unsigned integer type.

How do I bridge the NSUInteger as Int? I built something which is interface-compatible with UITabBarController in Objective-C, but the selectedIndex method is translated as UInt, not Int.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Doctor w-rw-rw- posted:

Apologies if this has already been covered, but the docs appear incorrect:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html


How do I bridge the NSUInteger as Int? I built something which is interface-compatible with UITabBarController in Objective-C, but the selectedIndex method is translated as UInt, not Int.

There's an initializer on Int that should do it, I don't remember the name.

Doctor w-rw-rw-
Jun 24, 2008

rjmccall posted:

There's an initializer on Int that should do it, I don't remember the name.

Not sure I understand. Is the suggested solution to pass in Int(foo) for all Swift calls to that method? Is there any Objective-C I can write (i.e. add an attribute or something) that will cause the NSUInteger parameter in the Objective-C method signature to resolve as an Int in the Swift method signature, as is the case for the tab bar controller?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Oh, I see. Can you not just change the parameter to NSInteger? ObjC isn't too picky about mismatches there.

I believe the rule we're applying is that (1) we consider our own headers to be too inconsistent about it and so always import as Int but (2) want to honor your code's choices, in part because user code uses such types in a much broader variety of ways than system headers do.

Doctor w-rw-rw-
Jun 24, 2008

rjmccall posted:

Oh, I see. Can you not just change the parameter to NSInteger? ObjC isn't too picky about mismatches there.

I believe the rule we're applying is that (1) we consider our own headers to be too inconsistent about it and so always import as Int but (2) want to honor your code's choices, in part because user code uses such types in a much broader variety of ways than system headers do.

I want to be consistent with that inconsistency, because I'm mimicking another class's interface. That, and NSUInteger makes semantic sense where NSInteger does not. I'm happy to annotate/attribute my Objective-C code in whatever way I need to emulate it, but I'd appreciate the option.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I don't think there's currently a way to control it. You could define an extension in Swift which takes an int and forwards to the ObjC API, of course, but that's not ideal.

We're looking into a lot of ways to let system code finely control how their code is imported; a radar would be really helpful as a way to let us know that users are running into these problems, too.

brap
Aug 23, 2004

Grimey Drawer
I'm happy to see that generic extensions are working--at least for Array. When I option-click on the Array in extension Array { ... } it shows Array<T>, and you can just reference that T in your function definitions.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You should really have to redeclare the generic parameters there; the current model is so bad. But yeah, we did fix some bugs in it.

Morroque
Mar 6, 2013
I just started using Swift earlier this month. While I find it easier to work with when compared to Objective C, I'm struggling with how Swift doesn't seem to handle ambiguity all that well. Most of it stems from the use of AnyClass. The documentation says that you should only really specifically use AnyClass when you need the exact properties the AnyClass definition can offer, but the backwards compatibility with Foundation means that AnyClass keeps coming up anyway -- no matter how hard you try to avoid it and usually in the most inopportune of places.

Has anyone heard the timeframe on when class var will be implemented? I'm currently storing my static variables in struct wrappers, but it all seems a little roundabout still...

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
class vars are properties of the class, meaning that the class and each of its subclasses all get their own independent instances of the property. That's not completely equivalent to the var-in-a-nested-struct trick, which makes a true global, unless the class has no subclasses. (It's also why the feature isn't implemented yet.)

Do you mean AnyObject, or are you really asking about AnyClass?

Morroque
Mar 6, 2013

rjmccall posted:

class vars are properties of the class, meaning that the class and each of its subclasses all get their own independent instances of the property. That's not completely equivalent to the var-in-a-nested-struct trick, which makes a true global, unless the class has no subclasses. (It's also why the feature isn't implemented yet.)

Huh. Maybe I misunderstood the purpose of it listed in the documentation? (Not like I've been able to test it myself, at least.)

So like, if I'm understanding that right, if I were to have an object called Shape, which is a superclass to the objects Triangle and Square, and shape has a class var of totalExistingShapes that starts at zero and increments++ by one every time it init()'s... then would the calls of Triangle.totalExistingShapes and Square.totalExistingShapes return different values?

rjmccall posted:

Do you mean AnyObject, or are you really asking about AnyClass?

The bulk of my work so far has been with custom-defined classes, so I'd wager it's about AnyClass half of the time. The other half might be AnyObject, or just Any, like in the case of fetching things from NSMutableArray or something. I'm still new to it, so its hard to tell. There is a temptation to program Swift like I would program Javascript since the syntax is so similar, but I can't really do that since Swift definitely has its own quirks that I'm still figuring out.

Like, let's say I have an NSMutableArray filled with instances of a type of object with an interior variable/property and I want to update one specifically, I feel like I should be able to say array.objectAtIndex(i).property = newvalue, but objectAtIndex returns an Any/AnyObject and not the type that I already know is in there, so Xcode won't really recognize the property being assigned, and there really isn't any room in there to cast an as?-statement either. This is weird to me, because I feel like I managed to accomplish similar things in Objective C before using those squarebracket calls that got so terribly nested all the time, but it's been a while since I last did anything major in ObjC so I don't know if I'm just imagining that.

Maybe I'm just too used to working in languages that are loosely typed...

Morroque fucked around with this message at 06:51 on Oct 20, 2014

brap
Aug 23, 2004

Grimey Drawer
Use swift arrays of you can. The casting really can be a bitch. I encountered my dictionary access issue again and forgot how I resolved it in here:

code:

self.property = aDictionary["Key"] as? TheType //doesn't work

var cursor: AnyObject? = aDictionary["Key"]
self.property = cursor as? TheType //works

edit: it's a [String : AnyObject] by the way

brap fucked around with this message at 07:06 on Oct 20, 2014

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

rjmccall posted:

Huh. It should definitely be letting you ask for that method with AnyObject-based dispatch. That's a bug.

As a workaround, try just throwing @objc on the implementations of that method that you're hoping to find.

It turns out that Swift demands the selector exists on some protocol somewhere visible to it, then it will allow it. No need to cast or anything, the selector must simply exist.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Ender.uNF posted:

It turns out that Swift demands the selector exists on some protocol somewhere visible to it, then it will allow it. No need to cast or anything, the selector must simply exist.

Oh. Yeah. That's true in ObjC, too.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Morroque posted:

So like, if I'm understanding that right, if I were to have an object called Shape, which is a superclass to the objects Triangle and Square, and shape has a class var of totalExistingShapes that starts at zero and increments++ by one every time it init()'s... then would the calls of Triangle.totalExistingShapes and Square.totalExistingShapes return different values?

Yep. You can, of course, make a global variable and just have Shape define a computed property that uses it if those are the semantics you want.

Morroque posted:

Maybe I'm just too used to working in languages that are loosely typed...

Yeah, I suspect you're fighting the type system.

shodanjr_gr
Nov 20, 2007
So doesn't Xcode 6 support creating a Swift app for OS X through the new project wizard? I get the option for iOS apps but not for OSX...

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

shodanjr_gr posted:

So doesn't Xcode 6 support creating a Swift app for OS X through the new project wizard? I get the option for iOS apps but not for OSX...

Xcode 6.1 brings Swift to OS X. Check the App Store for an update!

If you're using 6.1 already then I dunno.

shodanjr_gr
Nov 20, 2007

pokeyman posted:

Xcode 6.1 brings Swift to OS X. Check the App Store for an update!

If you're using 6.1 already then I dunno.

Doh...that makes sense.

Geno
Apr 26, 2004
STUPID
DICK
What are your thoughts on this?

quote:

What is Phoenix?

Phoenix is a free and open version of Apple's Swift programming language.

https://ind.ie/phoenix/

cowtown
Jul 4, 2007

the cow's a friend to me

Geno posted:

Phoenix is a free and open version of Apple's Swift programming language.
https://ind.ie/phoenix/

Am I missing something, or is this just a lexer/parser and nothing else?

feedmegin
Jul 30, 2008

cowtown posted:

Am I missing something, or is this just a lexer/parser and nothing else?

Looks like that to me. Does this guy have any actual experience of writing compilers?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

LLVM, jazz hands, ship it

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
The grammar is even provided in the book, so it's not like there was significant reverse engineering to be done -- did he just copy-and-paste it and then run yacc or ANTLR on it?

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Open Letter-Driven Development

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I look forward to this effort in the true spirit of friendly and open competition.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Time for Swiftspider?

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

rjmccall posted:

Oh. Yeah. That's true in ObjC, too.

I thought it only requires the selector to exist anywhere, not specifically in a protocol?

Also: my kingdom for a way to get the list of possible values for an enum (and the list of associated types for each one if any).

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Ender.uNF posted:

I thought it only requires the selector to exist anywhere, not specifically in a protocol?

Yes. Is that not true in Swift? If you've declared it somewhere, and exposed it to ObjC with @objc, that's worth a bug.

Ender.uNF posted:

Also: my kingdom for a way to get the list of possible values for an enum (and the list of associated types for each one if any).

It's on the bucket list. Er, at least the list of possible values for payload-less enums is. Meaningfully enumerating payloaded enums would probably require static or dynamic metaprogramming; what's your goal?

  • Locked thread