3

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.

suisied
  • 426
  • 1
  • 6
  • 19

2 Answers2

4

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.

donnywals
  • 7,241
  • 1
  • 19
  • 27
0

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.

Ted Huinink
  • 846
  • 1
  • 7
  • 14
  • 2
    That doesn't initialise anything, it just tells the compile that it will be initialized / have a value at some point in time. – donnywals Aug 30 '15 at 10:43