Replacing the first occurrence in Swift
I have some Swift code ( currently written for Mac ), which is supposed to generate random sentences. I have most of it completed, but it is reaplacing all occurrences of placeholders with the same noun/verb/adjective/etc. when I only want it to replace the first.
//
// ViewController.swift
// Funny Sentance Generator
//
// Created by Ethan Manzi on 5/March/2018.
// Copyright © 2018 Ethan Manzi. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var textOutput: NSTextField!
let nouns = ["dog","cat","ferret"]
let plNouns = ["dogs","cats","ferrets"]
let verbs = ["run","eat","fart"]
let ingVebs = ["jumping","hitting","cooking"]
let adj = ["cold","hot","dirty"]
let places = ["Flordia", "Mexio", "Earth"]
let sentances = [
"I [verb](ed) the [adjective] [noun].",
"The [adjective] [noun] went to the [adjective] [noun]'s home in [place]. It was [adjective]."
]
let keys = ["[noun]","[pl. noun]","[verb]","[ingVerb]","[adjective]","[place]"]
@IBAction func nwq(_ sender: Any) {
let x = arc4random_uniform(UInt32(sentances.count))
var disSent = sentances[Int(x)]
while (keys.contains(where: disSent.contains)) {
disSent = disSent.replacingOccurrences(of: "[noun]", with: nouns[Int(arc4random_uniform(UInt32(sentances.count)))])
disSent = disSent.replacingOccurrences(of: "[pl. noun]", with: plNouns[Int(arc4random_uniform(UInt32(plNouns.count)))])
disSent = disSent.replacingOccurrences(of: "[verb]", with: verbs[Int(arc4random_uniform(UInt32(verbs.count)))])
disSent = disSent.replacingOccurrences(of: "[ingVerb]", with: ingVebs[Int(arc4random_uniform(UInt32(ingVebs.count)))])
disSent = disSent.replacingOccurrences(of: "[adjective]", with: adj[Int(arc4random_uniform(UInt32(adj.count)))])
disSent = disSent.replacingOccurrences(of: "[place]", with: places[Int(arc4random_uniform(UInt32(places.count)))])
}
textOutput.stringValue = disSent
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
Everything else it working, it randomly picks the proper kind from the array, and displays the content back to the user, but it only generates one verb for all verb placeholders, which isn't what I want.