Jeff Meatball Yang
Jeff Meatball Yang

Reputation: 39027

Appending string to UILabel text?

I'm starting to develop for the iPhone. I have a beginner-type question, I'm sure:

I have this, which works:

testLabel.text = [NSString stringWithFormat:@"%@ to %@", testLabel.text, newLabelText];

I wish I could use the "+=" operator, but I get a compile error (Invalid operands to binary +, have 'struct NSString *' and 'struct NSString *'):

testLabel.text += [NSString stringWithFormat:@"to %@", newLabelText];

Why can't I do this?

Also, how can I shorten my first snippet of code?

Upvotes: 4

Views: 10490

Answers (5)

lochiwei
lochiwei

Reputation: 1358

try this:

// usage: label.text += "abc"
public func += (a:inout String?, b:String) {
    a = (a ?? "") + b
}

give this custom operator a try:

let label = UILabel()
label.text = "abc"
label.text += "_def"
print(label.text)    // “abc_def”

Upvotes: 0

ACBurk
ACBurk

Reputation: 4428

NSString are NOT mutable (they can't be changed), that's why you can't use +=.

NSMutableString can be changed. You might be able to use them here.

Your code is already pretty minimal. Objective-C is a expressive language so just get used to long, descriptive function and variable names.

Upvotes: 1

Adam Rosenfield
Adam Rosenfield

Reputation: 400274

You can't use the += operator because C and Objective-C do not allow operator overloading. You're trying to use += with two pointer types, which is not allowed -- if the left-hand side of a += expression has a pointer type, then the right-hand side must be of an integral type, and the result is pointer arithmetic, which is not what you want in this case.

Upvotes: 5

zaph
zaph

Reputation: 112857

That can't be done because ObjectiveC does not support it, ObjectiveC is a small layer over C.

testLabel.text = [testLabel.text stringByAppendingFormat:@" to %@", newLabelText];

Upvotes: 2

Tim
Tim

Reputation: 60130

Think about using an NSMutableString - you can use the appendString: method, as in:

NSMutableString *str = [@"hello" mutableCopy];
[str appendString:@" world!"];

Upvotes: 5

Related Questions