changing characters.string from nil to "" - ios

var addressTxtFldArray = addressTxtFld.text!.characters.split{$0 == " "}.map(String.init)
if addressTxtFldArray.count == 1 {
addressTxtFldArray[1] = ""
addressTxtFldArray[2] = ""
addressTxtFldArray[3] = ""
addressTxtFldArray[4] = ""
addressTxtFldArray[5] = ""
} else if addressTxtFldArray.count == 2 {
addressTxtFldArray[2] = ""
addressTxtFldArray[3] = ""
addressTxtFldArray[4] = ""
addressTxtFldArray[5] = ""
} else if addressTxtFldArray.count == 3 {
addressTxtFldArray[3] = ""
addressTxtFldArray[4] = ""
addressTxtFldArray[5] = ""
} else if addressTxtFldArray.count == 4 {
addressTxtFldArray[4] = ""
addressTxtFldArray[5] = ""
} else {
addressTxtFldArray[5] = ""
}
var cityTxtFldArray = cityTxtFld.text!.characters.split{$0 == " "}.map(String.init)
if cityTxtFldArray.count == 1 {
cityTxtFldArray[1] = ""
}
var stateTxtFldArray = stateTxtFld.text!.characters.split{$0 == " "}.map(String.init)
if stateTxtFldArray.count == 1 {
stateTxtFldArray[1] = ""
}
var addressTxtFldDestArray = addressTxtFldDest.text!.characters.split{$0 == " "}.map(String.init)
if addressTxtFldDestArray.count == 1 {
addressTxtFldDestArray[1] = ""
addressTxtFldDestArray[2] = ""
addressTxtFldDestArray[3] = ""
addressTxtFldDestArray[4] = ""
addressTxtFldDestArray[5] = ""
} else if addressTxtFldDestArray.count == 2 {
addressTxtFldDestArray[2] = ""
addressTxtFldDestArray[3] = ""
addressTxtFldDestArray[4] = ""
addressTxtFldDestArray[5] = ""
} else if addressTxtFldDestArray.count == 3 {
addressTxtFldDestArray[3] = ""
addressTxtFldDestArray[4] = ""
addressTxtFldDestArray[5] = ""
} else if addressTxtFldDestArray.count == 4 {
addressTxtFldDestArray[4] = ""
addressTxtFldDestArray[5] = ""
} else {
addressTxtFldDestArray[5] = ""
}
var cityTxtFldDestArray = cityTxtFldDest.text!.characters.split{$0 == " "}.map(String.init)
if cityTxtFldDestArray.count == 1 {
cityTxtFldDestArray[1] = ""
}
var stateTxtFldDestArray = stateTxtFldDest.text!.characters.split{$0 == " "}.map(String.init)
if stateTxtFldDestArray.count == 1 {
stateTxtFldDestArray[1] = ""
}
Hello, so as you can see I am breaking down strings into individual words on the string, and then if they are empty, change them to "" instead of nil. However, it seems like this is still returning nil. Any suggestions would be greatly appreciated.

I don't see how you're not getting "Index out of range" errors with this code.
If you simply want to make sure your addressTxtFldArray variable always has exactly 6 entries, I would suggest something like this:
var addressTxtFldArray = (addressTxtFld.text!.characters
.split{$0 == " "}.map(String.init)
+ Array(count:6, repeatedValue:"")
)[0..<6]

If you really need the text field array to be field with "" instead of nil, I suggest you create a secondary array to save you from doing all the if comparisons and setting it to "".
var arrayContainer = [String](count: 10, repeatedValue: "")
let addressTxtFldArray = text.characters.split{$0 == " "}.map(String.init)
for (index,value) in addressTxtFldArray.enumerate()
{
arrayContainer[index] = value
}
print( arrayContainer)

Related

How to integrate PayUMoney in swift

I want to integrate the PayUMoney SDK in my app using
I am using this link to integrate PayUMoney: How to integrate PayU Money in swift
I can see only the option to pay by credit card referring to the link's sample code however it is not showing up the net banking option. I don't understand what I am doing wrong in my code.
Here's what I have tried -
import UIKit
import PlugNPlay
import CommonCrypto
class PaymentVC: UIViewController {
var type = String()
var email = String()
var name = String()
var phone = String()
var address = String()
var state = String()
var zipcode = String()
var officetype = Int()
var TotalAmmount = String()
override func viewDidLoad() {
super.viewDidLoad()
continueWithCardPayment()
// Do any additional setup after loading the view.
}
#IBAction func backButtonAction(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
func continueWithCardPayment()
{
var paymentParam = PUMTxnParam()
paymentParam.key = "Zegfsgh"
paymentParam.merchantid = "7085776"
paymentParam.txnID = "xyz"
paymentParam.phone = "8770338859"
paymentParam.amount = TotalAmmount
paymentParam.productInfo = "Nokia"
paymentParam.surl = "https://test.payumoney.com/mobileapp/payumoney/success.php"
paymentParam.furl = "https://test.payumoney.com/mobileapp/payumoney/failure.php"
paymentParam.firstname = "john"
paymentParam.email = "john#john.com"
paymentParam.environment = PUMEnvironment.test
paymentParam.udf1 = "udf1"
paymentParam.udf2 = "udf2"
paymentParam.udf3 = "udf3"
paymentParam.udf4 = "udf4"
paymentParam.udf5 = "udf5"
paymentParam.udf6 = ""
paymentParam.udf7 = ""
paymentParam.udf8 = ""
paymentParam.udf9 = ""
paymentParam.udf10 = ""
paymentParam.hashValue = self.getHashForPaymentParams(paymentParam)
// paymentParam. = ""
// Set this property if you want to give offer:
// paymentParam.userCredentials = ""
PlugNPlay.presentPaymentViewController(withTxnParams: paymentParam, on: self, withCompletionBlock: { paymentResponse, error, extraParam in
if error != nil {
UIUtility.toastMessage(onScreen: error?.localizedDescription, from: .none)
} else {
var message = ""
if paymentResponse?["result"] != nil && (paymentResponse?["result"] is [AnyHashable : Any]) {
print(paymentResponse!)
message = "Hello Asad sucess"
// message = paymentResponse?["result"]?["error_Message"] as? String ?? ""
// if message.isEqual(NSNull()) || message.count == 0 || (message == "No Error") {
// message = paymentResponse?["result"]?["status"] as? String ?? ""
// }
} else {
message = paymentResponse?["status"] as? String ?? ""
}
UIUtility.toastMessage(onScreen: message, from: .none)
}
})
PlugNPlay.presentPaymentViewController(withTxnParams: paymentParam, on: self, withCompletionBlock: .none)
}
func sha512(_ str: String) -> String {
let data = str.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
data.withUnsafeBytes({
_ = CC_SHA512($0, CC_LONG(data.count), &digest)
})
return digest.map({ String(format: "%02hhx", $0) }).joined(separator: "")
}
func getHashForPaymentParams(_ txnParam: PUMTxnParam?) -> String? {
let salt = "vw8LigfjD"
var hashSequence: String? = nil
if let key = txnParam?.key, let txnID = txnParam?.txnID, let amount = txnParam?.amount, let productInfo = txnParam?.productInfo, let firstname = txnParam?.firstname, let email = txnParam?.email, let udf1 = txnParam?.udf1, let udf2 = txnParam?.udf2, let udf3 = txnParam?.udf3, let udf4 = txnParam?.udf4, let udf5 = txnParam?.udf5, let udf6 = txnParam?.udf6, let udf7 = txnParam?.udf7, let udf8 = txnParam?.udf8, let udf9 = txnParam?.udf9, let udf10 = txnParam?.udf10 {
hashSequence = "\(key)|\(txnID)|\(amount)|\(productInfo)|\(firstname)|\(email)|\(udf1)|\(udf2)|\(udf3)|\(udf4)|\(udf5)|\(udf6)|\(udf7)|\(udf8)|\(udf9)|\(udf10)|\(salt)"
}
let hash = self.sha512(hashSequence!).description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
return hash
}
func paymentResponseReceived(notify:NSNotification) {
print(notify)
}
}

What is the replacement for AKSampler.loadMelodicSoundFont in AudioKit 4.2?

I had to upgrade from AudioKit 4.0 to AudioKit 4.2 due to an incompatibility of AudioKit 4.0 with latest swift language and Xcode.
However, now my project cannot be compiled because loadMelodicSoundFont is not a member of AKSampler anymore while I'm using this method to load sf2 sound file.
I could find a documentation for 4.1 only on http://audiokit.io/docs/ and 4.1 has loadMelodicSoundFont apparently. And no documentation for 4.2 I could find.
So what is the replacement for this method in AudioKit 4.2?
The new AKSampler class in the latest versions of AudioKit is an entirely new custom sampler. However, as of right now it no longer handles SoundFont files natively (that's what your sf2 file is).
The easiest way for you would simply be to switch to AKAppleSampler, which is the fully featured sampler from previous versions of AudioKit. It relies on the Apple AU code and is still able to load SoundFont files.
So in practice you would simply rename your references to AKSampler to AKAppleSampler in your code.
You can rewrite the loadBetterSFZ sampler-extension function in the AKsampler example. This only reads for the included converted files and presumes the sample file is the last part of a region.
I did so and now I can use to sfz converted sf2 files from polyphony(windows) and sforzando and read the file for as far as I understand AKSampler can hold. I made a class to read the sfz file into a data structure that holds the data for reuse. For the sampler I wrote an extension that loads from the created data. Its all quick and dirty (I am not a programmer!). There are many different ways sfz files seem to be structured and I only tried a dozen or so.
example: add class SFZData to conductor in the example
get data with func SFZData.parseSFZ(folderPath: String, sfzFileName: String)->SFZ?
use SFZ for the extension in sampler: func loadSFZData(sfz:SFZ)
//here is what I did(all last versions and works on iPhone 6s)
import Foundation
class regionData {
var lovel: Int32 = -1 //not set, use group
var hivel: Int32 = -1
var lokey: Int32 = -1
var hikey: Int32 = -1
var pitch: Int32 = -1
var tune: Int32 = 0
var transpose: Int32 = 0
var loopmode: String = ""
var loopstart: Float32 = 0
var loopend: Float32 = 0
var startPoint: Float32 = 0
var endPoint: Float32 = 0
var sample: String = ""
init(){
}
}
class groupData {
var lovel: Int32 = 0
var hivel: Int32 = 127
var lokey: Int32 = 0
var hikey: Int32 = 127
var pitch: Int32 = 60
var loopmode: String = ""
var sample: String = ""
var regions = [regionData]()
init(){
}
}
class globalData {
var samplePath = ""
var lovel: Int32 = 0
var hivel: Int32 = 127
var sample: String = ""
var groups = [groupData]()
//ampdata?
//filterdata?
init(){
}
}
class ampData {
// in global and or group?
}
class SFZ {
var sfzName = ""
var baseURL : URL!
var global = globalData()
var group = [groupData?]()
init(){
//
}
}
class SFZdata {
var sfzChuncks = [String:SFZ]()
init(){
}
func getData(folderPath: String, sfzFileName: String)->SFZ?{
let sfzdata = sfzChuncks[sfzFileName]
if sfzdata != nil {
return sfzdata
}
return parseSFZ(folderPath:folderPath,sfzFileName:sfzFileName)
}
func parseSFZ(folderPath: String, sfzFileName: String)->SFZ? {
//let globalName = "<global>"
//let groupName = "<group>"
let regionName = "<region>"
var filePosition : String.Index
var chunck = ""
var data: String
let sfz = SFZ()
//stopAllVoices()
//unloadAllSamples()
let baseURL = URL(fileURLWithPath: folderPath)
let sfzURL = baseURL.appendingPathComponent(sfzFileName)
do {
data = try String(contentsOf: sfzURL, encoding: .ascii)
}catch {
debugPrint("file not found")
return nil
}
sfz.sfzName = sfzFileName
filePosition = data.startIndex
while filePosition != data.endIndex {
chunck = findHeader(data: data,dataPointer: &filePosition)
switch chunck {
case "<global>":
//get end of gobal and read data
let globaldata = readChunck(data: data, dataPointer: &filePosition)
let trimmed = String(globaldata.trimmingCharacters(in: .whitespacesAndNewlines))
sfz.global = readGlobal(globalChunck: trimmed)!
break
case "<group>":
//get end of group and read data
//first read this one the
let groupdata = readChunck(data: data, dataPointer: &filePosition)
let trimmed = String(groupdata.trimmingCharacters(in: .whitespacesAndNewlines))
let mygroup = readGroup(groupChunck: trimmed)
chunck = findHeader(data: data, dataPointer: &filePosition)
while chunck == regionName {
//read region and append
let regiondata = readChunck(data: data, dataPointer: &filePosition)
let trimmed = String(regiondata.trimmingCharacters(in: .whitespacesAndNewlines))
let myRegion = readRegion(regionChunck: trimmed)
mygroup?.regions.append(myRegion)
chunck = findHeader(data: data, dataPointer: &filePosition)
}
if chunck != regionName && filePosition != data.endIndex {
//back to before header if ! endoffile
filePosition = data.index(filePosition, offsetBy: -(chunck.count))
}
sfz.group.append(mygroup)
break
// case region without group ? ignore
default:
//ignore
break
}
}
sfz.baseURL = URL(fileURLWithPath: folderPath)
sfzChuncks.updateValue(sfz, forKey: sfzFileName)
return sfz
}
func findHeader(data:String, dataPointer:inout String.Index)->(String) {
if dataPointer == data.endIndex {
return ("")
}
while dataPointer != data.endIndex {
if data[dataPointer] == "<" { break }
dataPointer = data.index(after: dataPointer)
}
if dataPointer == data.endIndex {
return ("")
}
let start = dataPointer
while dataPointer != data.endIndex {
if data[dataPointer] == ">" { break }
dataPointer = data.index(after: dataPointer)
}
dataPointer = data.index(after: dataPointer)
if dataPointer == data.endIndex {
return ("")
}
return (String(data[start..<dataPointer]))
}
func readChunck(data:String,dataPointer:inout String.Index)->String{
var readData = ""
if dataPointer == data.endIndex { return readData }
while dataPointer != data.endIndex {
if data[dataPointer] == "<" {
break
} else {
readData.append(data[dataPointer])
dataPointer = data.index(after: dataPointer)
}
}
if dataPointer == data.endIndex {return readData }
if data[dataPointer] == "<" {
dataPointer = data.index(before: dataPointer)
}
return readData
}
func readGlobal(globalChunck:String)->globalData?{
let globaldata = globalData()
var samplestring = ""
var global = globalChunck
for part in globalChunck.components(separatedBy: .newlines){
if part.hasPrefix("sample") {
samplestring = part
}
}
if samplestring == "" {
//check for structure
if global.contains("sample") {
//get it out
var pointer = global.startIndex
var offset = global.index(pointer, offsetBy: 6, limitedBy: global.endIndex)
var s = ""
while offset != global.endIndex {
s = String(global[pointer..<offset!])
if s.contains("sample") {break}
pointer = global.index(after: pointer)
offset = global.index(pointer, offsetBy: 6, limitedBy: global.endIndex)
}
if s.contains("sample") {
//read to end
samplestring = String(global[pointer..<global.endIndex])
}
}
}
if samplestring != "" {
globaldata.sample = samplestring.components(separatedBy: "sample=")[1].replacingOccurrences(of: "\\", with: "/")
global = global.replacingOccurrences(of: samplestring, with: "", options: NSString.CompareOptions.literal, range: nil)
}
for part in global.components(separatedBy: .newlines) {
if part.hasPrefix("lovel") {
globaldata.lovel = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("hivel") {
globaldata.hivel = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("sample") {
globaldata.sample = part.components(separatedBy: "sample=")[1].replacingOccurrences(of: "\\", with: "/")
}
}
return globaldata
}
func readGroup(groupChunck:String)->groupData?{
let groupdata = groupData()
var samplestring = ""
var group = groupChunck
for part in groupChunck.components(separatedBy: .newlines){
if part.hasPrefix("sample") {
samplestring = part
}
}
if samplestring == "" {
//check for structure
if group.contains("sample") {
//get it out
var pointer = group.startIndex
var offset = group.index(pointer, offsetBy: 6, limitedBy: group.endIndex)
var s = ""
while offset != group.endIndex {
s = String(group[pointer..<offset!])
if s.contains("sample") {break}
pointer = group.index(after: pointer)
offset = group.index(pointer, offsetBy: 6, limitedBy: group.endIndex)
}
if s.contains("sample") {
//read to end
samplestring = String(group[pointer..<group.endIndex])
}
}
}
if samplestring != "" {
groupdata.sample = samplestring.components(separatedBy: "sample=")[1].replacingOccurrences(of: "\\", with: "/")
group = group.replacingOccurrences(of: samplestring, with: "", options: NSString.CompareOptions.literal, range: nil)
}
for part in group.components(separatedBy: .whitespacesAndNewlines) {
if part.hasPrefix("lovel") {
groupdata.lovel = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("hivel") {
groupdata.hivel = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("lokey") {
groupdata.lokey = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("hikey") {
groupdata.hikey = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("pitch_keycenter") {
groupdata.pitch = Int32(part.components(separatedBy: "=")[1])!
}else if part.hasPrefix("loop_mode") {
groupdata.loopmode = part.components(separatedBy: "=")[1]
}
}
return groupdata
}
func readRegion(regionChunck:String)->regionData{
let regiondata = regionData()
var samplestring = ""
var region = regionChunck
for part in regionChunck.components(separatedBy: .newlines){
if part.hasPrefix("sample") {
samplestring = part
}
}
// this for formats in wich ther are no newlines between region elements
if samplestring == "" {
//check for structure
if region.contains("sample") {
//get it out
var pointer = region.startIndex
var offset = region.index(pointer, offsetBy: 6, limitedBy: region.endIndex)
var s = ""
while offset != region.endIndex {
s = String(region[pointer..<offset!])
if s.contains("sample") {break}
pointer = region.index(after: pointer)
offset = region.index(pointer, offsetBy: 6, limitedBy: region.endIndex)
}
if s.contains("sample") {
//read to end
samplestring = String(region[pointer..<region.endIndex])
}
}
}
if samplestring != "" {
regiondata.sample = samplestring.components(separatedBy: "sample=")[1].replacingOccurrences(of: "\\", with: "/")
region = region.replacingOccurrences(of: samplestring, with: "", options: NSString.CompareOptions.literal, range: nil)
}
for part in region.components(separatedBy: .whitespacesAndNewlines) {
if part.hasPrefix("lovel") {
regiondata.lovel = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("hivel") {
regiondata.hivel = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("key=") {
regiondata.pitch = Int32(part.components(separatedBy: "=")[1])!
regiondata.lokey = regiondata.pitch
regiondata.hikey = regiondata.pitch
}else if part.hasPrefix("transpose") {
regiondata.transpose = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("tune") {
regiondata.tune = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("lokey") { // sometimes on one line
regiondata.lokey = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("hikey") {
regiondata.hikey = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("pitch_keycenter") {
regiondata.pitch = Int32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("loop_mode") {
regiondata.loopmode = part.components(separatedBy: "=")[1]
} else if part.hasPrefix("loop_start") {
regiondata.loopstart = Float32(part.components(separatedBy: "=")[1])!
} else if part.hasPrefix("loop_end") {
regiondata.loopend = Float32(part.components(separatedBy: "=")[1])!
}else if part.hasPrefix("offset") {
regiondata.startPoint = Float32(part.components(separatedBy: "=")[1])!
}
else if part.hasPrefix("end") {
regiondata.endPoint = Float32(part.components(separatedBy: "=")[1])!
}
}
return regiondata
}
}
extension for sampler:
func loadSFZData(sfz:SFZ){
stopAllVoices()
unloadAllSamples()
for group in sfz.group {
for region in (group?.regions)! {
var sd = AKSampleDescriptor()
if region.pitch >= 0 {
sd.noteNumber = region.pitch
} else {
sd.noteNumber = (group?.pitch)!
}
var diff = Float(1)
if region.tune != 0 {
let fact = Float(pow(1.000578,Double(region.tune.magnitude)))
if region.tune < 0 {
diff *= fact
} else {
diff /= fact
}
}
sd.noteFrequency = Float(AKPolyphonicNode.tuningTable.frequency(forNoteNumber: MIDINoteNumber(sd.noteNumber-region.transpose)))*diff
if region.lovel >= 0 {
sd.minimumVelocity = region.lovel
} else {
sd.minimumVelocity = (group?.lovel)!
}
if region.hivel >= 0 {
sd.maximumVelocity = region.hivel
} else {
sd.maximumVelocity = (group?.hivel)!
}
if region.lokey >= 0 {
sd.minimumNoteNumber = region.lokey
} else {
sd.minimumNoteNumber = (group?.lokey)!
}
if region.hikey >= 0{
sd.maximumNoteNumber = region.hikey
} else {
sd.maximumNoteNumber = (group?.hikey)!
}
sd.loopStartPoint = region.loopstart
sd.loopEndPoint = region.loopend
var loopMode = ""
if region.loopmode != "" {
loopMode = region.loopmode
} else if group?.loopmode != "" {
loopMode = (group?.loopmode)!
}
sd.isLooping = loopMode != "" && loopMode != "no_loop"
sd.startPoint = region.startPoint
sd.endPoint = region.endPoint
// build sampldescriptor from region
// now sample
var sample = region.sample
if sample == "" { sample = (group?.sample)! }
if sample == "" { sample = sfz.global.sample}
if sample != "" {
let sampleFileURL = sfz.baseURL.appendingPathComponent(sample)
if sample.hasSuffix(".wv") {
loadCompressedSampleFile(from: AKSampleFileDescriptor(sampleDescriptor: sd, path: sampleFileURL.path))
} else {
if sample.hasSuffix(".aif") || sample.hasSuffix(".wav") {
let compressedFileURL = sfz.baseURL.appendingPathComponent(String(sample.dropLast(4) + ".wv"))
let fileMgr = FileManager.default
if fileMgr.fileExists(atPath: compressedFileURL.path) {
loadCompressedSampleFile(from: AKSampleFileDescriptor(sampleDescriptor: sd, path: compressedFileURL.path))
} else {
do {
let sampleFile = try AKAudioFile(forReading: sampleFileURL)
loadAKAudioFile(from: sd, file: sampleFile)
} catch {
debugPrint("error loading audiofile")
}
}
}
}
} //if sample
} //region
} //group
buildKeyMap()
restartVoices()
}

Swift concatenate string based on different values

I need to concatenate a string based on some logic but I cant figure out how to do it.
Example:
var filterString: String = ""
var hasFilter: Bool = false
if let catId = param["catid"] {
filterString += "cat_id=\(catId)"
hasFilter = true
}
if let subCatId = param["subcatid"] {
filterString += "sub_cat_id=\(subCatId)"
hasFilter = true
}
if let locationId = param["stateid"] {
filterString += "location_id=\(locationId)"
hasFilter = true
}
if hasFilter == true {
query.filters = filterString
}
This will only work if I have ONE filter in my query
Eg: query.filters = "location_id=4"
But if I happend to have two or more filters my query will break eg:
query.filters = "location_id=4cat_id=3"
If I have more then one filter I need to seperate it with a AND statement like this:
query.filters = "location_id=4 AND cat_id=3"
But I cant figure out how to do it since I never know what order the filter will come in or if there even will be one or more filters to begin with
Edit
I seem to get it working by:
var filterString: String = ""
var hasFilter: Bool = false
if let catId = param["catid"] {
filterString += "cat_id=\(catId)"
hasFilter = true
}
if let subCatId = param["subcatid"] {
if hasFilter == true {
filterString += " AND sub_cat_id=\(subCatId)"
} else {
filterString += "sub_cat_id=\(subCatId)"
}
hasFilter = true
}
if let locationId = param["stateid"] {
if hasFilter == true {
filterString += " AND location_id=\(locationId)"
} else {
filterString += "location_id=\(locationId)"
}
hasFilter = true
}
if hasFilter == true {
query.filters = filterString
}
One solution would be to put the filters into an array and then if the array isn't empty, combine the array values with an " AND " separator.
var filters : [String] = []
if let catId = param["catid"] {
filters.append("cat_id=\(catId)")
}
if let subCatId = param["subcatid"] {
filters.append("sub_cat_id=\(subCatId)")
}
if let locationId = param["stateid"] {
filters.append("location_id=\(locationId)")
}
if filters.count > 0 {
query.filters = filters.joined(separator: " AND ")
}
Maybe you can first create an array and append all the filters.
After that create another variable to append all the values in the array.
Another option using inline if statements:
var param = ["catid" : "111", "subcatid" : "222", "stateid" : "333"]
var filterString = ""
if let catId = param["catid"] {
filterString = "cat_id=\(catId)"
}
if let subCatId = param["subcatid"] {
filterString.appendContentsOf(filterString.characters.count > 0 ? " AND sub_cat_id=\(subCatId)" : "sub_cat_id=\(subCatId)")
}
if let locationId = param["stateid"] {
filterString.appendContentsOf(filterString.characters.count > 0 ? " AND location_id=\(locationId)" : "location_id=\(locationId)")
}
print(filterString)
if (filterString.characters.count > 0) {
query.filters = filterString
}

Random array string getting nil

I am using the random range function to my array string. Also I am using a filter to not repeat to my array string, but sometimes my first random string is nil.
Random range code:
func randomNumber(range: Range<Int> = 1...6) -> Int {
let min = range.startIndex
let max = range.endIndex
return Int(arc4random_uniform(UInt32(max - min))) + min
}
I'm getting nil from the firstItem:
var a = cities[randomNumber(0...80)]
if Marmara.contains(a){
firstItem = a
print(firstItem) //It's getting nil sometimes.
var filteredForSecond = Marmara.filter{$0 != firstItem}
secondItem = filteredForSecond[randomNumber(0...filteredForSecond.count-1)]
print(secondItem)
var filteredForThird = Marmara.filter{$0 != secondItem && $0 != firstItem}
thirdItem = filteredForThird[randomNumber(0...filteredForThird.count-1)]
print(thirdItem)
var filteredForFourth = Marmara.filter{$0 != thirdItem && $0 != secondItem && $0 != firstItem}
print(fourthItem)
fourthItem = filteredForFourth[randomNumber(0...filteredForFourth.count-1)]
//sehirler.removeAtIndex(s)
print("\(firstItem), \(secondItem), \(thirdItem), \(fourthItem)")
}
I have an "81" string in the array using this code. What should I do to fix this nil string problem?
I would at least make the following change. See if this fixes the problem.
var a = cities[randomNumber(0...cities.count-1)]
I solved the problem. I'm checking if it is nil, taking again random string and it's not getting nil anymore.
Here is the working code:
var a = cities[randomNumber(0...cities.count-1)]
while a.isEmpty{
a = cities[randomNumber(0...cities.count-1)]
}
if Marmara.contains(a) && a != ""{
firstItem = a
if firstItem.isEmpty{
print("nil")
}
print(firstItem)
var filteredForSecond = Marmara.filter{$0 != firstItem}
secondItem = filteredForSecond[randomNumber(0...filteredForSecond.count-1)]
print(secondItem)
var filteredForThird = Marmara.filter{$0 != secondItem && $0 != firstItem}
thirdItem = filteredForThird[randomNumber(0...filteredForThird.count-1)]
print(thirdItem)
var filteredForFourth = Marmara.filter{$0 != thirdItem && $0 != secondItem && $0 != firstItem}
print(fourthItem)
fourthItem = filteredForFourth[randomNumber(0...filteredForFourth.count-1)]
//sehirler.removeAtIndex(s)
print("\(firstItem), \(secondItem), \(thirdItem), \(fourthItem)")
}

How to show the current state you are located in when using reverseGeocodeLocation in swift

I'm testing out reverseGeocodeLocation with this app that shows your closest address. I've gotten everything to work except for the showing of the current state that you are in (IL, NY, ext.). How do I do that? This is my current code:
CLGeocoder().reverseGeocodeLocation(userLocation)
{ (placemarks, error) -> Void in
if error != nil
{
println(error)
}
else
{
let pm = CLPlacemark(placemark: placemarks![0] as CLPlacemark)
var subThoroughtare:String = ""
var thoroughfare:String = ""
var subLocality:String = ""
var subAdministrativeArea:String = ""
var postalCode:String = ""
var country:String = ""
if pm.subThoroughfare != nil {subThoroughtare = pm.subThoroughfare!}
if pm.thoroughfare != nil {thoroughfare = pm.thoroughfare!}
if pm.subLocality != nil {subLocality = pm.subLocality!}
if pm.subAdministrativeArea != nil {subAdministrativeArea = pm.subAdministrativeArea!}
if pm.postalCode != nil {postalCode = pm.postalCode!}
if pm.country != nil {country = pm.country!}
self.addressLabel.text = "\(subThoroughtare) \(thoroughfare) \n \(subLocality) \n \(postalCode) \n \(country)"
}
}
and the output is this (example location):
County Road 1760
79529
United States
for the state you want to look at the administrativeArea
let state = pm.administrativeArea;
If you look at the definition for the CLPlacemark class it shows..
var administrativeArea: String! { get } // state, eg. CA

Resources