Saturday 16 December 2017

Swift version 4 Search Strings Code examples

Tested in Playground for Xcode 9, Swift Version 4 (4.0.3) tested code samples:

-------------------------------------------------------------------------------------------
Swift 4 Xcode 9: Search for a string in a string with keyword: "contains"

let astring = "Hello dear blog readers, I love this, its is so simple"
let asubstring = "readers, I love"

if astring.lowercased().contains(asubstring.lowercased()) {
    print("the search gave: " + asubstring)

}
// returns the search gave: readers, I love

--------------------------------------------------------------------------------------------
Swift 4 Xcode 9Search for a string in an Array using "contains" and a filter thing:

let itemsArray = ["Google", "Goodbye", "Go go", "Hello"]
var filterdItemsArray = [String]()
var searchText = "Go go"

filterdItemsArray = itemsArray.filter { item in item.lowercased().contains(searchText.lowercased())}

print(filterdItemsArray)
// returns ["Run away"]


---------------------------------------------------------------------------
Swift 4 Xcode 9: Search for a string in an array using "contains" (but I didn't manage to lowercase it!)



let itemsArray = ["Zebra", "Lion", "Run away", "Leopard"]
var searchText = "Run away"

if itemsArray.contains(searchText) {
    print("the search gave: " + searchText) }

// returns the search gave: Run away


---------------------------------------------------------------------------
Swift 4 Xcode 9: Remove a character from a string using the filter keyword:


let mystring = "blubbery beach"
let filteredString = mystring.filter { $0 != "b" }

print (filteredString)
// returns luery each (takes out the bs from blubbery beach)

---------------------------------------------------------------------------
Swift 4 Xcode 9: String contains example:


print("one two three four".contains("two three"))
// returns: true

---------------------------------------------------------------------------

Swift 4 Xcode 9: Search a string with range of example:

var stringy = "well well, what have we here"

if stringy.lowercased().range(of:"what have") != nil {
    print("exists")

}
// returns: exists

---------------------------------------------------------------------------









No comments: