ios - How to determine if each element in an array contains a certain letter by making an array of a wordlist file (swift 2) -


i relatively new swift. attempting make program takes wordlist (in form of array of strings) , removes strings not contain user-chosen letter. so, if wordlist ["apple", "banana", "cherry", "date", "endive"] , user chooses letter "a" (this variable "centerletter"), "apple", "banana" , "date" returned, do contain letter a. code works when array inputted (wordlist) standard array ["apple", "banana"]. however, actual use code sorting through every word in english language, found in file "words.txt" (one of files in swift project).

i have assigned every word in words.txt (which separated /n) wordlist follows (this function):

func arrayfromcontentsoffilewithname(filename: string) -> [string]? {      let path = nsbundle.mainbundle().pathforresource("words", oftype: "txt")      var filecontents: string? = nil     {         filecontents = try string(contentsoffile: path!, encoding: nsutf8stringencoding)         return filecontents!.componentsseparatedbystring("\n")     } catch _ nserror {         return nil     } } 

i assign wordlist result of arrayfromcontentsoffilewithname("words.txt") so:

var wordlist = arrayfromcontentsoffilewithname("words.txt") 

then crunch wordlist code (attempting take out every word of wordlist not contain user-chosen letter ("a" in example). code works on standard array ["apple", "banana"], not on array made function arrayfromcontentsoffilewithname.

let centerlet:character = character(array(arrayliteral: centerletter.text!)[0]) 

// centerlet letter user chooses.

    var = 0; < wordlist?.count; i++ {         if wordlist![i].characters.contains(centerlet) {             print("i leaving in \(wordlist![i]) because contains center letter")         } else {             print("i removed \(wordlist![i]) because did not have center letter.")             wordlist?.removeatindex(i)             }         } 

how can convert words in words.txt standard swift array can remove every word in said array not contain letter? thanks.

you removing items in list while iterating through list index. modifying list while enumerating leads disaster, , delivers unexpected results.

how simple filter?

let filteredlist = wordlist.filter { !$0.characters.contains(letter) } 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -