[英]Binary operator '+' cannot be applied to operands of type 'String' and 'String exclamationmark
I am generating a QRCode with name, email and phone number of user which are entered in registration form. 我正在生成一个QRCode,其中包含用户的姓名,电子邮件和电话号码,该QRCode在注册表格中输入。 In RegistrationVC, I have used userdefaults to save all these 3 fields.
在RegistrationVC中,我已使用userdefaults保存所有这三个字段。 Now in my QRGenerate VC, with the help of user default I want to generate QR code, but throwing an error
现在在我的QRGenerate VC中,在用户默认设置的帮助下,我想生成QR码,但是会抛出错误
Binary operator '+' cannot be applied to operands of type 'String' and 'String!".
二进制运算符“ +”不能应用于类型为“字符串”和“字符串!”的操作数。
I am passing all three keys to a string (ieqrgeneratestring) and generating QRCodes. 我将所有三个键传递给一个字符串(ieqrgeneratestring)并生成QRCode。
phoneKeyValue = UserDefaults.standard.string(forKey: "phoneKey")
nameKeyValue = UserDefaults.standard.string(forKey: "nameKey")
emailidKeyValue = UserDefaults.standard.string(forKey: "emailIDKey")
var qrgeneratestring = nameKeyValue + emailidKeyValue + phoneKeyValue
if qrgeneratestring.isEmpty == false{
let ciImageFromQRCode = generateQRCodeFromString(strQR: qrgeneratestring)
let scaleX = (imgViewQRCode.frame.size.width / ciImageFromQRCode.extent.size.width)
let scaleY = (imgViewQRCode.frame.size.height / ciImageFromQRCode.extent.size.height)
let imgTransformed = ciImageFromQRCode.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
imgViewQRCode.image = UIImage(ciImage: imgTransformed)
}
string(forKey
returns an optional, you need to unwrap the three values and you have to declare the variables as non-optional string(forKey
返回一个可选值,您需要解开三个值,并且必须将变量声明为非可选
var phoneKeyValue = ""
var nameKeyValue = ""
var emailidKeyValue = ""
let defaults = UserDefaults.standard
phoneKeyValue = defaults.string(forKey: "phoneKey") ?? ""
nameKeyValue = defaults.string(forKey: "nameKey") ?? ""
emailidKeyValue = defaults.string(forKey: "emailIDKey") ?? ""
The UserDefaults method string(forKey:...)
returns an optional - that is a value that can either be of the type String, or nil. UserDefaults方法
string(forKey:...)
返回一个可选-该值可以是String类型或nil。
You need to unwrap the optional, either using exclamation mark !
您需要使用感叹号来打开可选选项
!
or using the coalesence operator ??
或使用合并运算符
??
. 。 This depends on whether you know the value can't be nil (so you use exclamation mark) or you provide a default value when the optional is a nil value.
这取决于您是否知道该值不能为nil(因此您使用感叹号),或者在可选值为nil值时提供默认值。
In this case I would use: 在这种情况下,我将使用:
phoneKeyValue = UserDefaults.standard.string(forKey: "phoneKey") ?? ""
nameKeyValue = UserDefaults.standard.string(forKey: "nameKey") ?? ""
emailidKeyValue = UserDefaults.standard.string(forKey: "emailIDKey") ?? ""
var qrgeneratestring = nameKeyValue + emailidKeyValue + phoneKeyValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.