Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
A bigger issue, thinking about it, than people making variables of things that should be constant, is that people make macros of things that should be constants, and they try arguing that they're the exact same, or even better.

Code:
#include <stdio.h>

const int a = 1;

int main()
{
    int a = 2;

    printf("%d\n", a);

    return 0;
}

Code:
Mac% clang const.c -W -Wextra
Mac% ./a.out
2

Swift looks great BTW. :)
 

Amazing Iceman

macrumors 603
Nov 8, 2008
5,348
4,111
Florida, U.S.A.
You'd hope so!

I haven't seen what the list of allowed characters in a variable name are, but considering unicode characters and emoji are allowed, I really hope the equals sign isn't!

You could really mess with the heads of fellow developers if it is!

heheh! Nah, it will all get fixed soon, you'll see.
I would drive everyone crazy if I use emoji character for my variables...

:) = false
 

ArtOfWarfare

macrumors G3
Nov 26, 2007
9,568
6,074
Code:
#include <stdio.h>

const int a = 1;

int main()
{
    int a = 2;

    printf("%d\n", a);

    return 0;
}

Code:
Mac% clang const.c -W -Wextra
Mac% ./a.out
2

And if had used a macro instead, you would have gotten a compiler error about having an invalid name for a variable - not a useful error that would have actually said what you did wrong. At least with a const it makes sense what happened - you're mistakenly shadowing the global variable with a local one... I was fairly certain clang's warnings would alert you to that kind of mistake... but I guess not if that's really all the output it gave you.
 

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
And if had used a macro instead, you would have gotten a compiler error about having an invalid name for a variable - not a useful error that would have actually said what you did wrong. At least with a const it makes sense what happened - you're mistakenly shadowing the global variable with a local one... I was fairly certain clang's warnings would alert you to that kind of mistake... but I guess not if that's really all the output it gave you.

Yeah, but that's the point. I would rather get a compiler error instead of carrying on happily without noticing, especially since the primary uses of #defines are in header files, which you likely have not read. Redefined consts gives a compile error, I give you that, but with clang redefined macros is a default warning, so with -Werror it's also a compile error.
 

AdonisSMU

macrumors 604
Oct 23, 2010
7,299
3,050
Glad to hear I'm not alone. Optionals look really great. Should end up with a lot fewer NPEs at runtime, and without having to use ugly annotations everywhere to explicitly say whether things may or may not use null.

A bigger issue, thinking about it, than people making variables of things that should be constant, is that people make macros of things that should be constants, and they try arguing that they're the exact same, or even better.

If there are macros in Swift, I haven't reached that section of the manual yet. Hopefully they're hygenic if they're present.

I love optionals. The nasty if if if if statement is gone in one swoop! The program is now easier to reason about. Optionals are like a better ternary operator...

----------

Not only that, but you should use "let", not "var". Goddamnit, this language was only revealed a few hours ago, and one of the first things they tell you is that you should be using constants as much as possible, and already you people are using variables where you should use constants. I've struggled mightily for the past few years trying to get people to use the "const" keyword in C/C++/Obj-C, but my efforts were in vain. I thought it was because const wasn't added until years after the first version of the language was unveiled. Now I see that it'll take more than it being there from the start for people to use it.

Maybe the syntax needs to be easier. Maybe

announcement "Hello World"

should work the way

let announcement = "Hello World"

does, so that it'll be fewer characters to type and people will somehow think it's better as a result (when really it's better for an entirely unrelated reason... and probably less readable... but at least safer).

Until I saw the presentation it never would've crossed my mind but Im totally sold on this idea. I questioned why they are using let so much but it makes great sense to prefer let over var. the compiler is there to help. Let it.
 

whooleytoo

macrumors 604
Aug 2, 2002
6,607
716
Cork, Ireland.
I love optionals. The nasty if if if if statement is gone in one swoop! The program is now easier to reason about. Optionals are like a better ternary operator...

I still don't think I'm wrapping my head around the benefits of optionals. As I see it, you'll still need to check optionals, just using a different syntax than comparing with nil?

i.e. instead of:

Code:
Object myObject;
if ((myObject = [Object getNewObject]))
...

you'll have

Code:
if let myObject = Object.getNewObject()
...

Unwrapping a nil optional results in a run-time error, so you still have to check. Am I missing something obvious? You can use optionals for non-object types, which obviously removes the need to have some kind of "default" or "non-assigned" value - is that the benefit?
 

AdonisSMU

macrumors 604
Oct 23, 2010
7,299
3,050
I still don't think I'm wrapping my head around the benefits of optionals. As I see it, you'll still need to check optionals, just using a different syntax than comparing with nil?

i.e. instead of:

Code:
Object myObject;
if ((myObject = [Object getNewObject]))
...

you'll have

Code:
if let myObject = Object.getNewObject()
...

Unwrapping a nil optional results in a run-time error, so you still have to check. Am I missing something obvious? You can use optionals for non-object types, which obviously removes the need to have some kind of "default" or "non-assigned" value - is that the benefit?
What happens when your if statement is dependent on several optional items before doing some sort of behavior?
 
Last edited:

ArtOfWarfare

macrumors G3
Nov 26, 2007
9,568
6,074
I still don't think I'm wrapping my head around the benefits of optionals. As I see it, you'll still need to check optionals, just using a different syntax than comparing with nil?

i.e. instead of:

Code:
Object myObject;
if ((myObject = [Object getNewObject]))
...

you'll have

Code:
if let myObject = Object.getNewObject()
...

Unwrapping a nil optional results in a run-time error, so you still have to check. Am I missing something obvious? You can use optionals for non-object types, which obviously removes the need to have some kind of "default" or "non-assigned" value - is that the benefit?

The benefit is that having a check is now enforced by the compiler. More errors caught by the compiler -> fewer errors found at runtime.
 

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
Unwrapping a nil optional results in a run-time error, so you still have to check. Am I missing something obvious? You can use optionals for non-object types, which obviously removes the need to have some kind of "default" or "non-assigned" value - is that the benefit?

I think that's mentioned somewhere in the book on Swift, having a non-value signify an error makes all other return values available.

Take strtol as an example from libc, if it fails to convert a value, 0 is returned, which means that it's not possible to determine between an error and the string "0", so you also need to check errno.
 

AdonisSMU

macrumors 604
Oct 23, 2010
7,299
3,050
The benefit is that having a check is now enforced by the compiler. More errors caught by the compiler -> fewer errors found at runtime.

They showed examples where an if statement needed to check several different optional items before doing something and I just refactored some nasty if logic at work because of this. Its nice that they have a nice clean syntax which accounts for the fact something may be optional. I still think avoiding nasty if logic even avoiding optionals is the way to go. However optionals do provide a nicer syntax than ugly nested if logic that is hard to read and reason about. Overall though I tend to think a nested if is potentially a code smell.

I tend to think he is looking at it the wrong way.

----------

I think that's mentioned somewhere in the book on Swift, having a non-value signify an error makes all other return values available.

Take strtol as an example from libc, if it fails to convert a value, 0 is returned, which means that it's not possible to determine between an error and the string "0", so you also need to check errno.

Another good point in some languages 0 is a value that is truthy.
 
Last edited:

pstoehr

macrumors member
Ahoi *,

it's very strange, it doesn't forgive you if you don't leave spaces between the variable and equal sign and declaration, as in these examples.

var test = 12 \\ no problem
var test=12 \\ Editor shows an error and the interpreter does nothing.

Also, in some cases, it is case-sensitive.

I'm pretty sure that this is wrong! The following code compiles without an error at my system:
Code:
import Foundation

var test=12 // No Problem

println("Hello, World with test \(test)!")

Best regards
Peter
 

whooleytoo

macrumors 604
Aug 2, 2002
6,607
716
Cork, Ireland.
What happens when your if statement is dependent on several optional items before doing some sort of behavior?

That's a bit vague, but based on your comment ago you mean would I use nested ifs, and no I wouldn't! :) If code was dependant on several optionals I'd use one of the following patterns, based on whether the optional can be recovered/recreated or not.

Code:
// If recoverable..
if ((!object = [Object getObject]))
    object = [Object createNewObject];
if ((!widget = [Widget getWidget]))
    widget = [Widget createNewWidget];
// Use object & widget here...

// Or, if not recoverable..
if ((!object = [Object getObject]))
    // throw exception indicating required object not available
if ((!widget = [Widget getWidget]))
    // throw exception indicating required widget not available 
// Use object & widget here...

The benefit is that having a check is now enforced by the compiler. More errors caught by the compiler -> fewer errors found at runtime.

Maybe so, I still need to read the optional sections again (and start playing around with it!), so I can figure out what run-time errors are still possible even with the introduction of optionals.

I think that's mentioned somewhere in the book on Swift, having a non-value signify an error makes all other return values available.

Take strtol as an example from libc, if it fails to convert a value, 0 is returned, which means that it's not possible to determine between an error and the string "0", so you also need to check errno.

While it's probably not the main reason why optionals were introduced, I can see how that alone is beneficial. Recently had a case where we used Boolean fields to store "Yes/No" answers from a form. Until the client requested that the forms can be saved as draft, meaning all bi-state (Boolean) fields now be tri-state (Yes | No | no-value).

They showed examples where an if statement needed to check several different optional items before doing something and I just refactored some nasty if logic at work because of this. Its nice that they have a nice clean syntax which accounts for the fact something may be optional. I still think avoiding nasty if logic even avoiding optionals is the way to go. However optionals do provide a nicer syntax than ugly nested if logic that is hard to read and reason about. Overall though I tend to think a nested if is potentially a code smell.

I tend to think he is looking at it the wrong way.

Maybe so! As above, I just need to figure out what run-time errors optionals prevent, or do optionals just let you fail slightly differently with slightly nicer syntax. :)
 

Amazing Iceman

macrumors 603
Nov 8, 2008
5,348
4,111
Florida, U.S.A.
Ahoi *,



I'm pretty sure that this is wrong! The following code compiles without an error at my system:
Code:
import Foundation

var test=12 // No Problem

println("Hello, World with test \(test)!")

Best regards
Peter

Hi Peter, you are correct, it compiled correctly. The following linse do give an error in the Playground:

var test= 12 // Problem
var test =12 // Problem
 

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
While it's probably not the main reason why optionals were introduced, I can see how that alone is beneficial. Recently had a case where we used Boolean fields to store "Yes/No" answers from a form. Until the client requested that the forms can be saved as draft, meaning all bi-state (Boolean) fields now be tri-state (Yes | No | no-value).

That's the reason mentioned in the book, but they use a Swift method ( toInt() ) as an example. A case of returning multiple states can also be handled with enums and bitsets, 0, 1, 2, 4 etc, or in the case of Swift tuples.
 

lpetrich

macrumors member
Nov 26, 2009
39
0
Here's a fancier exercise of programming-language features: 99 Bottles of Beer | Start To generate the stanzas of that song, it is necessary to do arithmetic, comparisons, conditional execution, looping, and assembling strings for output. So what might a Swift version look like?


I've been reading Apple's Swift book, and while it is not a good textbook on programming in general, it does a reasonable job of introducing features of that language.

Swift seems rather Python-like to me, but it has compile-time type checking rather than Python's run-time type checking. That and other Swift features, like declared constants, are good for catching various bugs in advance. That is good for software that will be widely distributed to nontechnical users, especially software whose source code will not be distributed along with it.

Swift does not have untyped macros like the C preprocessor. However, it does have generics, like C++ template functions and classes, and they do much of what the C preprocessor is often used for. Swift's declared constants, like C++ "const" ones, also do some of the C preprocessor's work, and do it in a type-safe manner.

I don't understand why some people dislike declared constants and type safety and other such features. I don't see how anyone could possibly love the C preprocessor, because it's so bug-prone.
 

dejo

Moderator emeritus
Sep 2, 2004
15,982
452
The Centennial State
I'm assuming the "=" is a valid character for names in Swift.

Not according to the Swift iBook:
Constant and variable names cannot contain mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
 

pstoehr

macrumors member
Ahoi,
I think in the second line you have declared a variable with the name "test=12". I'm assuming the "=" is a valid character for names in Swift.

the line
Code:
test=12
works great in Playground and as a normal Swift file!

As Iceman mentions the lines
Code:
var test1= 12
var test2 =12
will generate an error in both Playground and normal Swift files.

By using type annotations things get a little bit scary:
Code:
var test1:Int= 12  // Problem
var test2:Int =12  // Works

As the error message "Prefix/postfix "=" is reserved" is also strange, it seems to me that this behavior is a bug. Or can anyone give me an hint what a Prefix/Postfix = is?

Best regards
Peter
 

chown33

Moderator
Staff member
Aug 9, 2009
10,766
8,466
A sea of green
As the error message "Prefix/postfix "=" is reserved" is also strange, it seems to me that this behavior is a bug. Or can anyone give me an hint what a Prefix/Postfix = is?

Best regards
Peter

It might be referring to the parsing of operators like += *= and so on.

IIRC, Swift allows operators to be defined on new types (classes, enums). The names of these operators must be built from the existing set of characters used for operators. So supposing test1= is parsed as a potential operator, it's wrong because it contains letters and digits that are illegal in operators. It's also wrong as a symbol name because = is illegal in names.
 

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
It might be referring to the parsing of operators like += *= and so on.

IIRC, Swift allows operators to be defined on new types (classes, enums). The names of these operators must be built from the existing set of characters used for operators. So supposing test1= is parsed as a potential operator, it's wrong because it contains letters and digits that are illegal in operators. It's also wrong as a symbol name because = is illegal in names.

Swift has operator overloading if that's what you are referring to, but they are defined with the @postfix and @prefix keywords preceding the 'func' keyword. I don't see why that would be the issue here.
 

chown33

Moderator
Staff member
Aug 9, 2009
10,766
8,466
A sea of green
Swift has operator overloading if that's what you are referring to, but they are defined with the @postfix and @prefix keywords preceding the 'func' keyword. I don't see why that would be the issue here.

Sorry, I didn't mean that I thought the compiler was treating it as an operator definition. I meant I thought the compiler was treating it as a potential operator that had already been defined elsewhere. AFAIK, uses of a defined operator don't have any affixed @ notation.

If the tokenizer looks for foo= as a potential operator, then it's conceivable that this just happens to be the error message associated with that part of the tokenizer.

And really, I was just guessing. I've seen odd error messages when token-parsing doesn't split things in expected ways. Those usually get cleaned up as the parser is improved, but wacky things can still happen.
 

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
AFAIK, uses of a defined operator don't have any affixed @ notation.

Exactly, the @ keywords are used when a new function is defined for the operator.

If the tokenizer looks for foo= as a potential operator, then it's conceivable that this just happens to be the error message associated with that part of the tokenizer.

It would be very odd if it did that since no foo= operator has been defined, I also think that overloading is restricted to the normal operators. As far as I can tell, a tokenizer should stop when it finds '=' and not treat it as part of the type, in this case Int.
 

ArtOfWarfare

macrumors G3
Nov 26, 2007
9,568
6,074
As the error message "Prefix/postfix "=" is reserved" is also strange, it seems to me that this behavior is a bug. Or can anyone give me an hint what a Prefix/Postfix = is?

It seems to me that when the tokenizer is seeing this:

test1=

It breaks it down to:
test1 as one token
= as a second token, postfixed to test1.

The error seems to be that it's parsing = as a postfix instead of an infix operator.
 
Last edited:

subsonix

macrumors 68040
Feb 2, 2008
3,551
79
It seems to me that when the tokenizer is seeing this:

test1=

It breaks it down to:
test1 as one token
= as a second token, postfixed to test1.

But, as the error message explains, Apple has reserved = as a postfix operator without actually assigning any valid behavior to it.

So possibly the bug is that Apple hasn't made it so that = as a postfix works the same as = as an infix.

The Swift book mentions that white space is used to determine if an operator is postfix or prefix, which makes sense in the case of the ++ operator for example, but what is the difference between a postfix or prefix assignment operator. There shouldn't be any semantic difference between a=b, a = b, a= b and a =b as far as I can tell.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.