2

I don't understand why the type system lets me do this?

In other words I would expect this to crash when foo is passed to the function.

var foo:String!

func someFunction(_ bar:String?) {
    print("-- \(bar) --")
}

someFunction(foo)

=> writes "-- nil --"
mkorpela
  • 4,317
  • 2
  • 19
  • 21
  • 5
    Related: [Implicitly unwrapped optional assign in Xcode 8](http://stackoverflow.com/q/39633481/2976878) – [Swift 3 incorrect string interpolation with implicitly unwrapped Optionals](http://stackoverflow.com/q/39537177/2976878). In Swift 3, if IUOs can be type-checked as strong optionals, they will be. – Hamish Feb 15 '17 at 10:22
  • @Hamish could you post that as an answer? – mkorpela Feb 15 '17 at 10:26
  • Also related: http://stackoverflow.com/questions/39633481/implicitly-unwrapped-optional-assign-in-xcode-8. – Martin R Feb 15 '17 at 10:48
  • Different question same answer. – mkorpela Feb 15 '17 at 10:52
  • @MartinR That was the first Q&A I linked to ;) – Hamish Feb 15 '17 at 10:54
  • 1
    @Hamish: Sorry, I read that on the phone and did not notice that there are two links :) – Martin R Feb 15 '17 at 10:55

3 Answers3

2

As @Hamish so correctly points out here: https://stackoverflow.com/a/39537558/308189

If the expression can be explicitly type checked with a strong optional type, it will be. However, the type checker will fall back to forcing the optional if necessary.

And the comment on the answer explains why this question was asked:

As if it weren't bad enough that you have to use an IUO, now they're less useful and behave contradictorily. If I use one it's because I want it to be implicitly unwrapped. They should be called Schrödinger Optionals from now on. – Andreas

Community
  • 1
  • 1
mkorpela
  • 4,317
  • 2
  • 19
  • 21
  • 1
    I voted to close the question because of duplication possibility, I suggest you to close it :) – Ahmad F Feb 15 '17 at 10:51
1

Inside your someFunction you are printing the optional not String. that's why it is not crashing. if you want to print bar as String you have to unwrap the value.

Sahil
  • 9,096
  • 3
  • 25
  • 29
0
// This line will create variable named foo and type of it will be String! and value of it will be nil.
// It mean i can access this variable is force-wraped so it may dangerous but uses of this variable  without type checking compiler will not give any warning(ignore by compiler).
var foo:String!

// This function will accept `String` value or `nil`. 
func someFunction(_ bar:String?) {
    print("-- \(bar) --")
}

// So calling this function use of `foo`(valued nil) will not give any compiler issue.
someFunction(foo)
ERbittuu
  • 968
  • 8
  • 19