Reputation: 1
I am making a web application in Vapor.
I have an array of things, e.g :
["thing", "other thing", "third thing"]
I want to make empty string variables with the same names but " "
replaced with "+"
in a struct.
I cannot use a dictionary or an array as vapor wants individual variables in strings. The reason I cannot write them all manually is that I want to be able to add things to my array and not have to also add them somewhere else.
I can do the replacing by myself, I just need to know if it is possible to make variables out of the array elements.
I am new to Swift, I do not know where to start.
Thanks for helping
Upvotes: 0
Views: 212
Reputation: 551
I hope I understand you correctly. You could use @dynamicMemberLookup
to dynamically look for struct/class property. Here is an example but I don't know exactly where is your purpose to use this and if this would help you.
import Foundation
let replaced = ["thing", "other thing", "third thing"].map {$0.replacingOccurrences(of: " ", with: "_")}
@dynamicMemberLookup
struct User {
subscript(dynamicMember m: String) -> String? {
if replaced.contains(m) {
return "soemthing for that thing"
}
return nil
}
}
let u = User()
print(u.other_thing)
print(u.thinga)
Because + is not allowed in property names you must use _ insetad. If you realy want to access it with + you could do it with print(u[dynamicMember: "other+thing"])
. To use this you must also replace $0.replacingOccurrences
to replace " "
with +
.
Here is some more info about @dynamicMemberLookup
https://docs.swift.org/swift-book/ReferenceManual/Attributes.html
Upvotes: 0
Reputation: 6992
let array = ["thing", "other thing", "third thing"]
let newArray = array.map { $0.replacingOccurrences(of: " ", with: "+") }
print(newArray)
// ["thing", "other+thing", "third+thing"]
Upvotes: 2