0

As more-or-less a Ruby monoglot, this has never been clear to me... The answers to this question explain how type-safety functions in Swift (and generally, I am guessing), but doesn't answer 'why'? Surely there is some performance or security benefit, but what is it exactly? Or is the benefit purely the strictness of the value later on -- the developer has the benefit of knowing some function will definitely perform (.each on an Array, for instance) or when run.

What trade-offs am I unknowingly adopting when I do this in, say, Ruby

x = Float.new x = 3 x = "a" x = [a, "a", ['a'], {a: 'a'}] 

versus what benefits am I receiving in it's equivalent in Swift:

var v: String var x = 3 var y = "a" var z = [ a, "a", ['a'], ['a': 'a'] ] 

?

Apologies if this is too basic or redundant -- I didn't find a similar question searching SO.

2
  • Kind of all of the above - type safety helps with catching errors during development or at compile time, protects against memory errors, since the size of a memory that a variable points to won't ever change, and lets the compiler do optimizations it couldn't do in a non-type-safe language, among other things. You could start here: en.wikipedia.org/wiki/Type_safety Commented Jun 3, 2014 at 17:35
  • 2
    This isn't really a Swift question. Or a Ruby question. The tradeoffs of type-systems are discussed in many many articles on the web, as well as existing Stack Overflow questions such as stackoverflow.com/questions/125367/… Commented Jun 3, 2014 at 21:04

1 Answer 1

3

Type-Safety is not only helpful for run-time, but also for compile-time.
It can help sticking to certain rules, and making code more obvious.

Swift does still not check for types at run-time, but doing a check at compile-time will already help eliminating a lot of errors. In ObjC you could do something like this:

NSString *string = (NSString *)@123; 

Does it throw an error? No. Does it make sense to warn the developer when compiling? Of course!

Type-safety can make sense in many ways, so let's look at some examples.


Examples

Beware, some of this is pseudo code

Remember using id for every possible thing? Those days lie in the past!

Which one is more obvious?

var numbers: Array<Int> = [ 1, 2, 3, 4 ] 

or

NSArray *numbers = @[1, 2, 3, 4]; 

var fontAttributes: Dictionary<String, FontAttribute> = [ Font.Weight : FontWeight.Bold, Font.Decoration : FontDecoration.None, ] 

or

NSDictionary *fontAttributes = @{ Font.Weight : FontWeight.Bold, Font.Decoration : FontDecoration.None, } 

var predicate = Predicate<Person>({ person in person.name == "John" }) 

or

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.name == %@", @"John"]; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.