micyukcha micyukcha - 3 months ago 23
Swift Question

Realm column names vs Swift variable names

I'm trying to create a Realm database that has columns that contain special characters and are all numbers such as '2010' or 'Share%'.

I can create the Realm using Realm Browser and even create a Realm object using http://www.realmgenerator.eu/ but when I put the model in Xcode, Xcode complains about the naming conventions.

class Contract: Object {
dynamic var ContractID = 0
dynamic var 2016 = ""
dynamic var 2017 = ""
dynamic var 2018 = ""
dynamic var 2016% = ""
dynamic var 2017% = ""
dynamic var 2018% = ""


Is there some work around? I would love to avoid naming my columns Year2016 or 2017Percent or something lengthy given I want to surface this data in my app.

Answer

You have to follow the variable naming restriction of Swift. According to the Swift Programming Language Manual, "Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.". This explains why Xcode did not like the variable names and symbols in them, and there is no workaround for naming your variables as described in your question.