Password Generator Using Multiple Strings in Swift - swift

I'm new to coding and I'm trying to create a password generator. I've created one using a single array of strings (all lowercase or all uppercase). But I want to create using multiple arrays. I'm using Swift 5.3 (Xcode 13.2.1)
struct ContainCharacterSelection {
var containNumbers: Bool = true
var containLowerCharacters: Bool = true
var containUpperCharacters: Bool = true
var containSpecialCharacters: Bool = true
var containComplicatedCharacters: Bool = false
}
class PasswordGenerator {
let numbers = ["0","1","2","3","4","5","6","7","8","9"]
let lowerCharacters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
let upperCharacters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let specialCharacters = ["!","\"","§","$","%","&","/","(",")","=","?","+","*","#",",",";",".",":","-","_","#","<",">"]
let complicatedCharacters = ["^","[","]","{","}","\\","'","`","´"]
var password = ""
var passwordLenght = sliderValue
}
Thanks in advance.

Join an array of strings into a single string.
let numbers = ["0","1","2","3","4","5","6","7","8","9"]
let joinedNumbers = array.joined() //joinedNumbers equals to 0123456789
Join other arrays via the same way:
joinedLowerCharacters,joinedUpperCharacters.....
Then we concatenate these strings as a single string.
finalString = joinedNumbers+joinedLowerCharacters+joinedUpperCharacters+...
Now we could generate password using the finalString.

Something like this would work. This is relatively simple and does not actually check the existence of certain type of character. If you need to absolutely verify the existence of certain character type, you might have to do some weird recursion logic.
However, this should work in most of the simpler cases.
struct ContainCharacterSelection {
var containNumbers: Bool = true
var containLowerCharacters: Bool = true
var containUpperCharacters: Bool = true
var containSpecialCharacters: Bool = true
var containComplicatedCharacters: Bool = false
}
class PasswordGenerator {
let numbers = ["0","1","2","3","4","5","6","7","8","9"]
let lowerCharacters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
let upperCharacters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let specialCharacters = ["!","\"","§","$","%","&","/","(",")","=","?","+","*","#",",",";",".",":","-","_","#","<",">"]
let complicatedCharacters = ["^","[","]","{","}","\\","'","`","´"]
var password = ""
var passwordLength = 32
func generate(selections: ContainCharacterSelection) {
var includedChars: [String] = [];
if selections.containLowerCharacters {
includedChars += lowerCharacters;
}
if selections.containUpperCharacters {
includedChars += upperCharacters;
}
if selections.containNumbers {
includedChars += numbers;
}
if selections.containSpecialCharacters {
includedChars += specialCharacters
}
if selections.containComplicatedCharacters {
includedChars += complicatedCharacters
}
includedChars.shuffle()
// mind it that this could crash if your array is smaller than the passwordLength, in that case use alternative solution commented below
self.password = includedChars[..< passwordLength].joined(separator: "")
// let randoms = (0 ..< passwordLength)
// .map { _ in includedChars.randomElement() }
// .compactMap { $0 }
// self.password = randoms.joined(separator: "")
}
}
var selections = ContainCharacterSelection()
selections.containUpperCharacters = true
selections.containLowerCharacters = true
selections.containSpecialCharacters = true
let passwordGenerator = PasswordGenerator()
passwordGenerator.generate(selections: selections)
print("Password: ", passwordGenerator.password)

Related

Why does this sorting algorithm fail?

I developed the below algorithm to sort the array of dictionary items.
guard var imageUrlString = anyImage.value as? [String:AnyObject] else { return }
var values = [AnyObject]()
var keys = [String]()
var done = false
var j = 1
while !done {
for i in imageUrlString {
print(i.key, " this is the key")
if "media\(j)" == i.key {
values.append(i.value)
keys.append(i.key)
print(i, " This is teh i for in if ")
if imageUrlString.count == j {
done = true
break;
}
j+=1
} else {
print("No,,.")
}
}
}
The problem is that sometimes, for example, every time the first media is an image, it will loop forever. How can I solve that so that the algorithm can effectively sort the under all conditions?
It looks like you're really creating two parallel arrays: keys and values.
I went with creating those two arrays, sorted. Here's an example
var imageUrlString = [String: AnyObject]()
imageUrlString["media3"] = "whatever 3 content" as AnyObject
imageUrlString["media7"] = "whatever 7 content" as AnyObject
imageUrlString["media1"] = "whatever 1 content" as AnyObject
let keys = Array(imageUrlString.keys).sorted()
var values = [AnyObject]()
keys.forEach {
values.append(imageUrlString[$0]!)
}
print(keys)
print(values)

How to remove duplicate characters from a string in Swift

ruby has the function string.squeeze, but I can't seem to find a swift equivalent.
For example I want to turn bookkeeper -> bokepr
Is my only option to create a set of the characters and then pull the characters from the set back to a string?
Is there a better way to do this?
Edit/update: Swift 4.2 or later
You can use a set to filter your duplicated characters:
let str = "bookkeeper"
var set = Set<Character>()
let squeezed = str.filter{ set.insert($0).inserted }
print(squeezed) // "bokepr"
Or as an extension on RangeReplaceableCollection which will also extend String and Substrings as well:
extension RangeReplaceableCollection where Element: Hashable {
var squeezed: Self {
var set = Set<Element>()
return filter{ set.insert($0).inserted }
}
}
let str = "bookkeeper"
print(str.squeezed) // "bokepr"
print(str[...].squeezed) // "bokepr"
I would use this piece of code from another answer of mine, which removes all duplicates of a sequence (keeping only the first occurrence of each), while maintaining order.
extension Sequence where Iterator.Element: Hashable {
func unique() -> [Iterator.Element] {
var alreadyAdded = Set<Iterator.Element>()
return self.filter { alreadyAdded.insert($0).inserted }
}
}
I would then wrap it with some logic which turns a String into a sequence (by getting its characters), unqiue's it, and then restores that result back into a string:
extension String {
func uniqueCharacters() -> String {
return String(self.characters.unique())
}
}
print("bookkeeper".uniqueCharacters()) // => "bokepr"
Here is a solution I found online, however I don't think it is optimal.
func removeDuplicateLetters(_ s: String) -> String {
if s.characters.count == 0 {
return ""
}
let aNum = Int("a".unicodeScalars.filter{$0.isASCII}.map{$0.value}.first!)
let characters = Array(s.lowercased().characters)
var counts = [Int](repeatElement(0, count: 26))
var visited = [Bool](repeatElement(false, count: 26))
var stack = [Character]()
var i = 0
for character in characters {
if let num = asciiValueOfCharacter(character) {
counts[num - aNum] += 1
}
}
for character in characters {
if let num = asciiValueOfCharacter(character) {
i = num - aNum
counts[i] -= 1
if visited[i] {
continue
}
while !stack.isEmpty, let peekNum = asciiValueOfCharacter(stack.last!), num < peekNum && counts[peekNum - aNum] != 0 {
visited[peekNum - aNum] = false
stack.removeLast()
}
stack.append(character)
visited[i] = true
}
}
return String(stack)
}
func asciiValueOfCharacter(_ character: Character) -> Int? {
let value = String(character).unicodeScalars.filter{$0.isASCII}.first?.value ?? 0
return Int(value)
}
Here is one way to do this using reduce(),
let newChar = str.characters.reduce("") { partial, char in
guard let _ = partial.range(of: String(char)) else {
return partial.appending(String(char))
}
return partial
}
As suggested by Leo, here is a bit shorter version of the same approach,
let newChar = str.characters.reduce("") { $0.range(of: String($1)) == nil ? $0.appending(String($1)) : $0 }
Just Another solution
let str = "Bookeeper"
let newChar = str.reduce("" , {
if $0.contains($1) {
return "\($0)"
} else {
return "\($0)\($1)"
}
})
print(str.replacingOccurrences(of: " ", with: ""))
Use filter and contains to remove duplicate values
let str = "bookkeeper"
let result = str.filter{!result.contains($0)}
print(result) //bokepr

Realm/Swift: compilation error: Missing argument for parameter 'forPrimaryKey' in call

I'm trying to get my head around swift & realm, so I've created some kind of a test pad programme.
My model is defined like so
class RealmRecord: Object {
// properties
dynamic var id: Int = 0;
dynamic var text: String = ""
dynamic var var1: Double = 0.0
dynamic var var2: Int = 0
dynamic var var3: Double = 0.0
dynamic var var4: Int = 0
dynamic var cdate: Date = Date()
dynamic var cusr: String = ""
dynamic var mdate: Date = Date.distantPast
dynamic var musr: String = ""
dynamic var mcnt: Int = 0
// methods
convenience init(id: Int? = 0, text: String? = "", var1: Double? = 0.0,
var2: Int? = 0, var3: Double? = 0.0, var4: Int? = 0,
cusr: String? = "") {
self.init()
self.id = id!
self.text = text!
self.var1 = var1!
self.var2 = var2!
self.var3 = var3!
self.var4 = var4!
self.cdate = Date()
self.cusr = cusr!
self.mdate = Date.distantPast
self.musr = ""
self.mcnt = 0
} // init
override static func primaryKey() -> String? {
return "id"
} // primaryKey
} // RealmRecord
Persisting the data is accomplished by
try recRealm?.write {
recRealm?.add(self.rec, update: true)
} // try
But when adding the data retrieval via
if let inrec = self.recRealm?.object(RealmRecord.self) {
return inrec
} else {
return List<RealmRecord>()
} // if/else
I'm receiving an error message while compiling the code, reading
DataRealmRecord.swift:84:39: Missing argument for parameter 'forPrimaryKey' in call
Looking at the Realm documentation reveals only retrieving all persisted data--apparently without having a primary key defined--, or, alternatively, a single object, specified by the primary key.
Sifting through The Net brings up pretty much the same.
Given the model above, how can I retrieve all persisted data?
-- Sil68
EDIT
I've also defined a class facilitating this Realm model of mine, which basically carries out the following steps:
generate some random data;
persist data via the Realm model;
read data in again;
compare generated with read data.
The code
import Foundation
import RealmSwift
class DataRealmRecord {
// properties
private(set) var recDBPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
private(set) var recDBSubPath = "Persistency"
private(set) var recDBFile = "data.realm"
private(set) var recRealm: Realm?
private(set) var recRealmCfg: Realm.Configuration?
private(set) var rec = List<RealmRecord>()
private(set) var startTime = 0.0
private(set) var stopTime = 0.0
private(set) var runTime = 0.0
private(set) var outLog = ""
private(set) var realmOk = false
// methods
init() {
// assemble destination folder/database name
do {
try FileManager.default.createDirectory(atPath: recDBPath + "/" +
recDBSubPath,
withIntermediateDirectories: true,
attributes: nil)
recDBFile = recDBPath + "/" + recDBSubPath + "/" + recDBFile
realmOk = true
} catch let error as NSError {
outLog += error.localizedDescription
realmOk = false
} // do/try/catch
// configure realm database
if (realmOk) {
self.recRealmCfg = Realm.Configuration(fileURL: Foundation.URL(string: self.recDBFile))
do {
self.recRealm = try Realm(configuration: self.recRealmCfg!)
realmOk = true
} catch let error as NSError {
outLog += error.localizedDescription
realmOk = false
} // do/try/catch
} // if
} // init
// generate test data
func generateData(noRecs: Int? = 1000, simDat: SimulateData?) {
for i in 1...noRecs! {
let realmRec = RealmRecord(id: i,
text: String(format: "Record #%04d", i),
var1: simDat?.datnorm[i - 1] ?? 1.1,
var2: simDat?.datpois[i - 1] ?? 2,
var3: simDat?.datunif[i - 1] ?? 3.3,
var4: simDat?.datbern[i - 1] ?? 4,
cusr: "me")
self.rec.append(realmRec)
} // for
} // generateData
// retrieve test data from persistent storage
func loadData() -> List<RealmRecord> {
if let inrec = self.recRealm?.object(RealmRecord.self) {
return inrec
} else {
return List<RealmRecord>()
} // if/else
} // loadData
// save test data to persistent storage
func saveData() {
do {
try recRealm?.write {
recRealm?.add(self.rec, update: true)
} // try
} catch let error as NSError {
outLog += error.localizedDescription
} // do/try/catch
} // saveData
// compare two data sets
func compareData(rec1: List<RealmRecord>, rec2: List<RealmRecord>) -> Bool {
var rc = false
if rec1.count == rec2.count {
rc = true
for i in 0..<rec1.count {
rc = rc && (rec1[i] == rec2[i])
} // for
} // if
return rc
} // compareData
// run a full evaluation cycle
// (1) generate test data;
// (2) save test data to persistant storage;
// (3) retrieve test data from persistant storage;
// (4) compare generated data with retrieved data.
func fullCycle(noRecs: Int? = 1000, simDat: SimulateData?, prnData: Bool? = false) {
// start execution time measurement
self.startTime = Double(CFAbsoluteTimeGetCurrent())
// execute the full cycle
self.generateData(noRecs: noRecs, simDat: simDat) // (1)
self.saveData() // (2)
let rec2 = self.loadData() // (3)
let cmpRec = compareData(rec1: self.rec, rec2: rec2) // (4)
// stop execution time measurement & calculate elapsed time
self.stopTime = Double(CFAbsoluteTimeGetCurrent())
self.runTime = self.stopTime - self.startTime
} // fullCycle
} // DataRealmRecord
Issue at hand is, this code fails to compile due to the error message mentioned above (in method loadData()).
The Swift compiler is telling you that it thinks you're trying to call Realm.object(ofType:forPrimaryKey:), which retrieves a single object based on the value of its primary key. It sounds like you really want to call Realm.objects(_:) to retrieve all objects of a given type. Note that this returns a Results<T>, not a List<T>.

Reverse Strings without using predefined functions

Pardon me as I am a newbie on this language.
Edit: Is there a way to reverse the position of a array element?
I am trying to create a function that test the given input if its a palindrome or not. I'm trying to avoid using functions using reversed()
let word = ["T","E","S","T"]
var temp = [String]()
let index_count = 3
for words in word{
var text:String = words
print(text)
temp.insert(text, atIndex:index_count)
index_count = index_count - 1
}
Your approach can be used to reverse an array. But you have to
insert each element of the original array at the start position
of the destination array (moving the other elements to the end):
// Swift 2.2:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
reversed.insert(char, atIndex: 0)
}
print(reversed) // ["T", "S", "E", "T"]
// Swift 3:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
reversed.insert(char, at: 0)
}
print(reversed) // ["T", "S", "E", "T"]
The same can be done on the characters of a string directly:
// Swift 2.2:
let word = "TEST"
var reversed = ""
for char in word.characters {
reversed.insert(char, atIndex: reversed.startIndex)
}
print(reversed) // "TSET"
// Swift 3:
let word = "TEST"
var reversed = ""
for char in word.characters {
reversed.insert(char, at: reversed.startIndex)
}
print(reversed)
Swift 5
extension String {
func invert() -> String {
var word = [Character]()
for char in self {
word.insert(char, at: 0)
}
return String(word)
}
}
var anadrome = "god"
anadrome.invert()
// "dog"
Here's my solution:
extension String {
func customReverse() -> String {
var chars = Array(self)
let count = chars.count
for i in 0 ..< count/2 {
chars.swapAt(i, count - 1 - i)
}
return String(chars)
}
}
let input = "abcdef"
let output = input.customReverse()
print(output)
You can try it here.
func reverse(_ str: String) -> String {
let arr = Array(str) // turn the string into an array of all of the letters
let reversed = ""
for char in arr {
reversed.insert(char, at: reversed.startIndex)
}
return reversed
}
To use it:
let word = "hola"
let wordReversed = reverse(word)
print(wordReversed) // prints aloh
Another solution for reversing:
var original : String = "Test"
var reversed : String = ""
var c = original.characters
for _ in 0..<c.count{
reversed.append(c.popLast()!)
}
It simply appends each element of the old string that is popped, starting at the last element and working towards the first
Solution 1
let word = "aabbaa"
let chars = word.characters
let half = chars.count / 2
let leftSide = Array(chars)[0..<half]
let rightSide = Array(chars.reverse())[0..<half]
let palindrome = leftSide == rightSide
Solution 2
var palindrome = true
let chars = Array(word.characters)
for i in 0 ..< (chars.count / 2) {
if chars[i] != chars[chars.count - 1 - i] {
palindrome = false
break
}
}
print(palindrome)
static func reverseString(str : String) {
var data = Array(str)
var i = 0// initial
var j = data.count // final
//either j or i for while , data.count/2 buz only half we need check
while j != data.count/2 {
print("befor i:\(i) j:\(j)" )
j = j-1
data.swapAt(i, j) // swapAt API avalible only for array in swift
i = i+1
}
print(String(data))
}
//Reverse String
let str = "Hello World"
var reverseStr = ""
for char in Array(str) {
print(char)
reverseStr.insert(char, at: str.startIndex)
}
print(reverseStr)

Problems linking objects in realm swift

I am having problems linking objects in realm. I read the question and answer titled "Nested objects in realm" and tried the answer suggested but it did not work for me.
Here are my object classes:
import Foundation
import RealmSwift
class Job: Object {
dynamic var id = NSUUID().UUIDString
dynamic var name = ""
dynamic var address = ""
dynamic var phone = ""
dynamic var email = ""
dynamic var notes = ""
dynamic var material = 0.0
dynamic var edge = 0.0
dynamic var splash = 0.0
dynamic var discount = 0.0
dynamic var trip = 0.0
let rooms = List<Room>()
override static func primaryKey() -> String {
return "id"
}
}
import Foundation
import RealmSwift
class Room: Object {
dynamic var id = NSUUID().UUIDString
dynamic var name = ""
dynamic var material = 0.0
dynamic var edge = 0.0
dynamic var splash = 0.0
dynamic var sinkType = ""
dynamic var sinkModel = ""
dynamic var numberOfSinks = 0
dynamic var faucet = ""
dynamic var rangeType = ""
dynamic var notes = ""
dynamic var jobs: Job?
let countertops = List<Countertop>()
//var linksToJob: [Job] {
// return linkingObjects(Job.self, forProperty: "rooms")
//}
override static func primaryKey() -> String {
return "id"
}
}
import Foundation
import RealmSwift
class Countertop: Object {
dynamic var id = NSUUID().UUIDString
dynamic var depth = 0.0
dynamic var width = 0.0
dynamic var cabDescription = ""
dynamic var sqFt = 0.0
dynamic var room: Room?
//var linkToRoom: [Room] {
// return linkingObjects(Room.self, forProperty: "countertops")
//}
override static func primaryKey() -> String {
return "id"
}
}
Here are the functions I use to save the data:
#IBAction func saveButton() {
jobs.name = nameTF.text!
jobs.address = addressTF.text!
jobs.phone = phoneTF.text!
jobs.email = emailTF.text!
jobs.notes = notesTV.text!
jobs.discount = Double(discountTF.text!)!
jobs.material = Double(materialTF.text!)!
jobs.edge = Double(edgeTF.text!)!
jobs.splash = Double(splashTF.text!)!
jobs.trip = Double(tripTF.text!)!
do {
try! realm.write {
realm.add(jobs)
}
}
print(jobs)
// print(Realm.Configuration.defaultConfiguration.path!)
}
func saveData(){
rooms.name = nameTF.text!
rooms.material = Double(materialTF.text!)!
rooms.edge = Double(edgeTF.text!)!
rooms.splash = Double(splashTF.text!)!
rooms.notes = notesTV.text
rooms.sinkType = sinkTypeTF.text!
rooms.sinkModel = sinkModelTF.text!
rooms.numberOfSinks = Int(numberSinksTF.text!)!
rooms.faucet = faucetTF.text!
rooms.rangeType = rangeTF.text!
rooms.jobs?.id = keyValueLabel.text!
//rooms.linksToJob
do {
try! realm.write {
realm.add(rooms)
}
}
print(rooms)
}
and:
#IBAction func addNextButton(sender: AnyObject) {
// self.realm.beginWrite()
let realm = try! Realm()
if widthTF.text != "" {
Calculations.depth = Double(depthTF.text!)!
Calculations.width = Double(widthTF.text!)!
let depthAdded = depthTF.text
cabinetDepth.append(Double(depthAdded!)!)
let widthAdded = widthTF.text
cabinetWidth.append(Double(widthAdded!)!)
let descriptionAdded = pickerLabel.text
cabinetDescription.append(descriptionAdded!)
let runningTotal = Calculations.squareFeet()
squareFeetToBeAdded.append(runningTotal)
let sum = squareFeetToBeAdded.reduce(0,combine: {$0 + $1})
let roundedSqFt = Double(round(sum * 10) / 10)
sqFtLabel.text = "\(roundedSqFt)"
countertops.depth = Double(depthTF.text!)!
countertops.width = Double(widthTF.text!)!
countertops.cabDescription = pickerLabel.text!
countertops.sqFt = Double(sqFtLabel.text!)!
//countertops.linkToRoom
do {
try realm.write {
realm.add(countertops)
}
print(countertops)
} catch {
print("an error occurred")
}
widthTF.text = ""
numberTable.reloadData()
widthTF.becomeFirstResponder()
}
}
When I save the data and print the results here is what I get:
Job {
id = 00F95F55-54D8-426E-B483-C990A4171002;
name = Ken;
address = Address;
phone = phone;
email = email;
notes = Notes :;
material = 8;
edge = 0;
splash = 4;
discount = 1;
trip = 0;
rooms = RLMArray <0x7ffef9df29c0> (
);
}
Room {
id = 7D3F86B9-FCD7-4CB7-AD6E-9B8141A7390C;
name = Kitchen;
material = 9;
edge = 0;
splash = 4;
sinkType = Undermount Kitchen;
sinkModel = 50/50 Stainless Steel;
numberOfSinks = 1;
faucet = Single Hole;
rangeType = Free Standing Range;
notes = Notes:;
jobs = (null);
countertops = RLMArray <0x7ffef9df3720> (
);
}
Countertop {
id = 992B8BAE-392F-4513-85DC-CBA191D2AE08;
depth = 25.5;
width = 65;
cabDescription = Cabinet;
sqFt = 11.5;
room = (null);
}
As you can see the links return null.
Please tell me what I am doing wrong here.
Note: I comment out the linkingObjects in the models because it caused a crash. I'm not sure why.
You should use references to existing realm objects when adding them. So rather than this:
func saveData(){
rooms.name = nameTF.text!
rooms.material = Double(materialTF.text!)!
rooms.edge = Double(edgeTF.text!)!
rooms.splash = Double(splashTF.text!)!
rooms.notes = notesTV.text
rooms.sinkType = sinkTypeTF.text!
rooms.sinkModel = sinkModelTF.text!
rooms.numberOfSinks = Int(numberSinksTF.text!)!
rooms.faucet = faucetTF.text!
rooms.rangeType = rangeTF.text!
rooms.jobs?.id = keyValueLabel.text!
//rooms.linksToJob
do {
try! realm.write {
realm.add(rooms)
}
}
print(rooms)
}
You would use something like this:
let realm = try! Realm()
let room = realm.create(Room.self)
room.name = nameTF.text!
room.material = Double(materialTF.text!)!
...
let job = realm.create(Job.self)
job.name = "My job name"
...
room.job = job
Since it looks like you're entering these on separate screens, you will add a room, then you want to add a job:
if let existingJob = realm.objects(Job).filter("name == '\(jobNameToLookup)'").first {
room.job = existingJob
}
For a list, just do room.countertops.append(newCountetop), where newCountertop is the result of realm.create
Because you add each objects into the Realm individually without linking. If you'd like to link the objects, you should add the objects to the List properties, such like rooms and countertops. Also for to-one relationships, you should assign the object to the property.
So you need write the code something like the following:
...
rooms.faucet = faucetTF.text!
rooms.rangeType = rangeTF.text!
...
rooms.countertops.append(countertops)
...
jobs.rooms.append(rooms)
And,
...
countertops.rooms = rooms
...
rooms.jobs = jobs
For more details, see also the documents:
Thanks to Austin who got me on the right track. Here is the code that finally did it.
#IBAction func roomSaveNextBtnPushed(_ sender: UIButton) {
let room = Room()
room.roomName = roomTF.text!
room.material = materialTF.text!
room.edge = edgeTF.text!
room.job = realm.objects(Job.self).last
try! realm.write {
realm.add(room)
print(room)
}
}
The link is made in the ' realm.object(Job.self).last ' line of code. This adds a room to a job as expected.
The suggestion in Austin's example ' let room = realm.create(Room.self) ' caused an error, and the project would not compile.
I am using Xcode 8 with Swift 3 and Realm-swift 1.1.0
Thanks again to those who offered help.