1

I am looking to see if it is possible to get a string that has a variable in it from a plist.

So just like you would do normally.

let string1 = "a string variable"

print("this is \(string1)"

I wanted to just put in my plist file "this is \(string1)"

So how can you format it in a plist file or can you format it when you pull it out of the plist file into a String.

Or do I just need to rebuild the whole string after I pull it out of the plist file?

Thanks

EBM
  • 61
  • 1
  • 5

1 Answers1

2

The proper solution would be to use string formatting, not string interpolation.

Put the following value in the plist:

this is %@

Then load that value as needed. Use it with String(format:...).

let format = ... // the format string loaded from the plist
let string1 = "a string variable"
let result = String(format: format, string1)

If format is this is %@ then the result will be:

this is a string variable

Use %d, for Int variables. Use %f for Double. See the documentation on String Format Specifiers for more details on the format specifiers.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I don't think you should recommend that. As has often been pointed out, a variable format string is a huge security hole. `stringWithFormat` is meant to be used with literal format strings. Your technique works, obviously, but showing it to a beginner and recommending it seems irresponsible somehow. – matt Jun 20 '18 at 16:00
  • @matt I understand you lose compile-time checking when used this way but I'm not aware of the security issue. Do you have a reference for that? – rmaddy Jun 20 '18 at 16:03
  • It's something people used to say a lot over on the old Cocoa list at Apple. Even on one of your own answers here (https://stackoverflow.com/a/13696245/341994) it comes up in another answer (https://stackoverflow.com/a/13696242/341994), though of course that's hardly a "reference". – matt Jun 20 '18 at 16:10
  • So can I ask you what would be the safer way to do what I am looking for. I did some research and it looks like the string with format vulnerability is in conjunction with the print command. I am not using the print command. I am filling a text field with the string I am making. – EBM Jun 21 '18 at 03:58
  • 1
    @EBM I found this: https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/ValidatingInput.html#//apple_ref/doc/uid/TP40007246-SW3 There is no security risk with my suggestion because the format strings are not coming from a user or unknown source. You are in control of them. – rmaddy Jun 27 '18 at 16:17