variable was written but never used in Swift 2.0 & Xcode 7

4.5k Views Asked by At

When I create a variable without String() to initialize the variable an error shows up alerting, "variable not initialize", same error shows up when I directly assign

var username: String = usernameTextfieldSigup.text!

And when I initialize the variable using the code below,

var username: String = String()
username = usernameTextfieldSignup.text!

warning comes up, variable 'username' was written but never used.

I know I could just ignore these warnings but I'd like a cleaner code. I'm using Xcode7 beta5 release.

2

There are 2 best solutions below

0
donnywals On BEST ANSWER

You can declare the username without a value first:

var username: String 

and then assign a value to it in your initializer:

// replace with your (valid) initializer
func init() {
    username = usernameTextfieldSignup.text!
}

However, I'm sure that usernameTextfieldSignup.text won't have a value until the user ha actually provided a value. So in that case I would recommend to make username an optional so you can set it's value when you need to:

var username: String?

and then when setting it:

username = usernameTextfieldSignup.text

and when accessing it:

if let uname = username {
    // do something with the uname
}

Also, the variable 'username' was written but never used warning you're seeing is probably because you write to / initialise username but there's no code actually reading it, so it's kind of a useless variable according to the compiler then.

1
Ted Huinink On

To init an empty string you have to either make it explicit or optional like so:

let string: String!
let string: String?

You can do this with any datatype.