algorithm,swift,realm,text-segmentation , How can I fix this memory issue in my maximum matching algorithm with RealmSwift?

How can I fix this memory issue in my maximum matching algorithm with RealmSwift?


Tag: algorithm,swift,realm,text-segmentation

I wrote my own maximum matching function in Swift to divide Chinese sentences into words. It works fine, except with abnormally long sentences the memory usage goes up over 1 gb. I need help figuring out how to modify my code so that there isn't this memory problem. I'm not sure if it has to do with how I am using RealmSwift or if it is my algorithm in general.

Here is my code:

    func splitSentenceIntoWordsWithDictionaryMaximumMatching(string: String) -> [String] {
    var string = string
    var foundWordsArray: [String] = []
    var position = count(string)

    while position > 0
        var index = advance(string.startIndex, position)
        let partialString = string.substringToIndex(index)
        if let found = Realm().objects(Word).filter("simplified == '\(partialString)'").first
            position = position - 1
            var partialStringCount = count(partialString)
            while partialStringCount > 0
                string = dropFirst(string)
                partialStringCount -= 1
            position = count(string)
            index = advance(string.startIndex, position)
        else if count(partialString) == 1
            addNewEntryToDictionaryInTransaction(partialString, "", [partialString], partialString)
            var partialStringCount = count(partialString)
            while partialStringCount > 0
                string = dropFirst(string)
                partialStringCount -= 1
            position = count(string)
            index = advance(string.startIndex, position)
            position = position - 1
            index = advance(string.startIndex, position)

    return foundWordsArray


In this case, you should use autoreleasepool (see: Use Local Autorelease Pool Blocks to Reduce Peak Memory Footprint) in the loop:

    while position > 0 {
        autoreleasepool {
            var index = advance(string.startIndex, position)

BTW, your code has too many memory copy operations and O(N) operations on String.Index (count() and advance()), that may cause serious performance problems. Instead, you should effectively use String.Index something like this :

import Foundation

var  words:Set = ["今日", "献立", "魚", "味噌汁", "定食", "焼き魚", "です"]
func splitSentenceIntoWordsWithDictionaryMaximumMatching(string: String) -> [String] {
    var foundWordsArray: [String] = []
    var start = string.startIndex
    var end = string.endIndex

    while start != end {
        autoreleasepool { // In this case(using builtin `Set`), I think we don't need `autoreleasepool` here. But this is just a demo :)
            let partialString = string[start ..< end]
            if !words.contains(partialString) {
                if end.predecessor() != start { // faster way of `count(partialString) == 1`
                    end = end.predecessor()
                    return // we cannot use `continue` here because we are in `autoreleasepool` closure
            start = end
            end = string.endIndex

    return foundWordsArray

var str = "今日の献立は焼き魚定食と味噌汁です"
let result = splitSentenceIntoWordsWithDictionaryMaximumMatching(str)

debugPrintln(result) // ["今日", "の", "献立", "は", "焼き魚", "定食", "と", "味噌汁", "です"]
debugPrintln(words) // Set(["献立", "焼き魚", "今日", "魚", "味噌汁", "定食", "は", "と", "です", "の"])

I used builtin Set, but I think you can easily adopts your Realm codes here :)

ADDED: in reply to the comments:

reversed version:

var  words:Set = ["研究", "研究生", "生命", "起源"]
func splitSentenceIntoWordsWithDictionaryMaximumMatchingReversed(string: String) -> [String] {
    var foundWordsArray: [String] = []
    var start = string.startIndex
    var end = string.endIndex

    while start != end {
        autoreleasepool {
            let partialString = string[start ..< end]
            if !words.contains(partialString) {
                if start.successor() != end {
                    start = start.successor()
            end = start
            start = string.startIndex

    return foundWordsArray.reverse()

var str = "研究生命起源"
let result = splitSentenceIntoWordsWithDictionaryMaximumMatchingReversed(str)

debugPrintln(result) // ["研究", "生命", "起源"]


Unexpectedly found nil while unwrapping an Optional value - Plist

i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

Characters and Strings in Swift

Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways: let narrowNonBreakingSpace: Character = "\u{202f}" let narrowNonBreakingSpace = "\u{202f}" As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes...

How to do a “show (e.g Push)” segue programatically without animation?

How can I do a "show (e.g Push)" segue programatically without animation? None of the solutions I've found works the same way as the one in storyboard.

iOS 8 Swift CS193P Calculator Bug Switch Operation

I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

Identify that a string could be a datetime object

If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

Omitting the return type in Swift closures

I'm working through one of the examples at the very handy and colourfully named site here, specifically : func applyMutliplication(value: Int, multFunction: Int -> Int) -> Int { return multFunction(value) } applyMutliplication(2, {value in value * 3 }) Notice that the closure given when calling applyMultiplication() does not specify a...

Swift Singleton not Working

Trying to get a Singleton class going in Swift. I'm not getting any errors, but its also just plain not working properly. Here's the code: // The Singleton class: class DataWarehouse { class var sharedData:DataWarehouse { struct Static { static var onceToken : dispatch_once_t = 0 static var instance :...

Cannot invoke method with argument list of type KeyType in Swift

I am working on custom message dispatcher in Swift. I want to have dispatcher which can: dispatch enums as events or whatever what is Hashable. Every object which implements one protocol might be added as listeners Here is the code: import Foundation protocol EventDispatcherProtocol: class { typealias T: Hashable func...

Difference between stringByAppendingString and appendString in ios

What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

iOS 9 not opening Instagram app with URL SCHEME

The following URL opens on iOS 8.3 and lower, but it does not work and iOS 9 let instagramURL = NSURL(string: "instagram://app") Why won't the URL open?...

How to get time difference based on GMT on Swift

I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

Parse JSON output from AlamoFire

I am using the latest Alamofire to manage a GET http request to my server. I am using the following to GET and parse the JSON: Alamofire.request(.GET, "*******") .responseJSON {(request, response, JSON, error) in if let statusesArray = JSON as? NSArray{ if let aStatus = statusesArray[0] as? NSDictionary{ //OUTPUT SHOWN...

UITapGestureRecognizer sender is the gesture, not the ui object

I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

iOS Swift: Sound not playing on iPhone Simulator

In my iOS Swift application, and i am trying to play sound on click of a button. func playSound() { var audioPlayer = AVAudioPlayer() let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) } I am running the application in iOS iPhone Simulator. I have doorbell.mp3...

What's the equivalent of finally in Swift

I try to use the error handling modeling in Swift2. do { try NSFileManager.defaultManager().removeItemAtPath("path") } catch { // ... } finally { // compiler error. } But it seems that there is no finally keyword out there.How can I achieve try-catch-finally pattern in Swift.Any help is welcome....

How can I show ONLY the date (and not the time) using NSDateFormatter?

I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

How can I fix crash when tap to select row after scrolling the tableview?

I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...

Implementing Applovin Ads with Swift & SpriteKit

I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

Do I have to use both of these methods?

When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

Swift timer in milliseconds

I want to change the timer every millisecond but it doesnt work as expected. NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: Selector("advanceTimer:"), userInfo: nil, repeats: true); func advanceTimer(timer: NSTimer){ self.time += 0.001; let milliseconds = self.time * 100; let remaingMilliseconds = Int((milliseconds % 1000) / 10); let seconds = Int((milliseconds / 1000) %...

How to code a generic Swift class which stores a Generator of the same type

I'm trying to write a class which handles objects of a homogenous type, and I'd like to feed in those objects using an (otherwise arbitrary) Generator of the same type. In essence this: class MyGenericClass<T> { var source : GeneratorType var itemsProcessed = [ T ]() init(source: GeneratorType) { self.source...

Reverse ^ operator for decryption

I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

What is the best practice add video background view?

I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

Swift Range on the fly 1…12.contains(1) Cannot invoke 'contains' with (Int)

Is is not possible to create a range and call its contains method like this: 1...12.contains(1) When I create a var range = 1...12 and print its dynamicType I get a Swift.Range<Swift.Int>, so I'm guessing is not a type mismatch problem, or is it?...

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error

I have this instance method in an existing Obj-C UIImage category: - (UIImage *)applyDarkEffect; I'm trying to call it from a Swift file like so: self.backgroundImageView.image = UIImage.applyDarkEffect(image) But get this compiler error: Function produces expected type 'UIImage!'; did you mean to call it with '()'? ...

How to create UITableViewCells with complex content in order to keep scrolling fluent

I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

Dynamic programming: how to design algorithm for when there are two factors to consider?

I have the following problem and I only have a slight idea about it: Consider a tape storage problem. Given n files of length l1,...,ln and frequencies with which they are accessed f1,...,fn, where sum of all frequencies is 1 and 0<fi<1. "Optimal" means to minimize the average retrieval time...

Understanding Big-Ω (Big-Omega) notation

I was doing some reading on logarithms and the rate of growth of the running time of algorithms. I have, however, a problem understanding the Big-Ω (Big-Omega) notation. I know that we use it for 'asymptotic lower bounds', and that we can express the idea that an algorithm takes at...

Reference method from different class as curried function

There are two merge methods in RACSignal: - (RACSignal *)merge:(RACSignal *)signal; + (RACSignal *)merge:(id<NSFastEnumeration>)signals; When I write RACSignal.merge it references static method: class func merge(signals: NSFastEnumeration!) -> RACSignal! How to reference object method? I can't write self.merge, because it is in wrapper class and self is not RACSignal....

Does there exist an algorithm for iterating through all strings that conform to a particular regex?

I'm making a script to try and hack into an account whose login password is at least 8 characters long and includes at least 1 number, 1 special character and 1 capital letter. I will use brute force. Is there a compact, elegant and efficient way to iterate through every...

What is this algorithm mapping coordinates to numbers called?

I'm writing a program for visualizing crystals. As a part of the program, I have to generate all different basic points in a lattice structure. For those that aren't familiar with crystallography, you can find the most general cases of these structures here: The problem was that I wanted...

3 X 3 magic square recursively

I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

Parse and Swift Geopoints not saving

I have tried everything. No matter what my Geopoints will not save when using an actual device with xcode or using the simulator. if signUpError == nil { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { PFUser.currentUser()!.setValue(geoPoint, forKey: "location") } } I am not...

animating a view on top of uitableview

I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

AppleScript (or swift) add hours to time

I'm trying to add 8Hours to a date (from the clipboard) set date1 to the clipboard set newdate to date1 + (8 * hours) display dialog "Purchases were downloaded at " & newdate buttons {"OK"} default button 1 But this is not working as expected, I'm having the error Can’t...

Get NSString from NSMutableArray on Swift

How can I get NSString from NSMutableArray created with NSStrings in a for loop? I want to store in one NSString, all elements of NSMutableArray. This is my code: class Persona: NSObject { var edad: Int var altura: Double var nombre: NSString var apellido: NSString var cualidades: NSMutableArray init(edad:Int, altura:Double,...

MFMessageComposeViewControllerDelegate not being called

I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

Beacon / IOS CLLocationManager get current region

I'm doing a program who is looking for beacon, I implemented CLLocationManager and my apps works except one point. I'm calling startMonitoringForRegion() in order to get the didEnterRegion/didExitRegion callback. Inside these function I'm doing startRangingBeaconsInRegion()/stopRangingBeaconsInRegion() in order to get precise information when the user is in the beacon area. My...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

looping variable in swift

i want to change this variable become looping in swift: var image1 = UIImage(named: "image1") var image2 = UIImage(named: "image2") var image3 = UIImage(named: "image3") var image4 = UIImage(named: "image4") var image5 = UIImage(named: "image5") var image6 = UIImage(named: "image6") var image7 = UIImage(named: "image7") images.append(image1!) images.append(image2!) images.append(image3!) images.append(image4!) images.append(image5!)...

Can't figure out coder aDecoder: NSCoder

I'm making an app for archiving books, I'm at the point of hooking up a button to save the data, but I can't get past the initialisation. Here is the error Xcode is giving me : Property 'self.bookStore' not initialised at super.init call. And here is my code : import...

How to add checkbox to uicollectionview in swift

some time ago someone already asked this question and a few answers were given but i didn't really understand any of them. So i was wondering if anyone could please write an easy to understand tutorial on how to do the things shown on the image below: I would...

PFUser not unwrapped - swift

I'm beginning to learn swift with parse and i've run into this error: "Value of optional type 'PFUser?' not unwrapped; did you mean to use '!' or '?' I can't seem to get it to work... PFFacebookUtils.logInWithPermissions(["public_profile", "user_about_me", "user_birthday"], block: { user, error in if user == nil { println("the...

How to save text field value in uicollectionviewcell

hi i have text field in uicollectionviewcell so what i need it example : when i edit text filed value in row 5 and i done it and go to text filed in row 20 to edit value the collectionview has reloaded and forget value in row 5, so i...

iOS Keyboard “Done” button load action

I'm trying to get "Done" button on to load an action, preferably the action that I have for my button. Here's the UITextField declaration let someTextField = UITextField() Trying to add a target to the textField someTextField.addTarget(self, action: "loginActionButton", forControlEvents: .EditingDidEndOnExit) ...

create a popup window with just a textview/string and a button SWIFT ios 8

I am very new to ios 8 and swift but I have not found a way to make a simple popup window whenever a button is pushed. I payed for tutorials and they still don't cover it. All i would like is for when the user pushes a button (the...

Build error after I localized Info.plist

I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...