简体   繁体   中英

How to use StringByAppendingFormat in XCode6

Code:

var postString: NSString = NSString .stringByAppendingFormat("userName=\(userName) & password = \(Password)")

Why I am getting error as:

(NSString, CVarArgType...) -> NSString' is not convertible to NSString.

stringByAppendingFormat: is an instance method on NSString , not a class method. Therefore, you can't call it with NSString.stringByAppendingFormat(...) , you have to call it on an exiting string:

var someExistingString = "..."
var postString = someExistingString.stringByAppendingFormat("userName = %@ & password = %@", userName, password)

That being said, you don't need to use stringByAppendingFormat if you're just constructing a new string from scratch, you can use Swift's String Interpolation directly:

var postString = "userName = \(userName) & password = \(password)"

You're getting that error because you're trying to call an instance method stringByAppendingFormat on a the class NSString . Here's an example that compiles:

var userName = "Dave"
var Password = "password"

var select = "SELECT * FROM users WHERE "

var postString: NSString = select.stringByAppendingFormat("userName=\(userName) & password = \(Password)")

Note : You never want to do something like this because of SQL Injection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM