Simple code in C++ Builder XE8 - c++builder-xe8

I want that code for C++ Builder XE8
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var str = listBox1.SelectedItem.ToString();
if (str == "A")
{
textBox1.Text = "You have selected A";
}
else if (str == "B")
{
textBox1.Text = "You have selected B";
}
else
{
textBox1.Text = "You have not selected A or B";
}
}

Perhaps the following C++ Builder could be like this:
private:
void listBox1_SelectedIndexChanged(void *sender, EventArgs *e)
{
auto str = listBox1::SelectedItem->ToString();
if (str == "A")
{
textBox1->Text = "You have selected A";
}
else if (str == "B")
{
textBox1->Text = "You have selected B";
}
else
{
textBox1->Text = "You have not selected A or B";
}
}

Related

Trying to return value from firebase querysnaphsot completion handler inside function

I'm trying to return a value produced from an asynchronous block of code (from my completion handler) for my function validateFields(), however I'm not sure how to do that.
func validateFields() -> Bool
{
//Other else if statements
//...
else if !(usernameTextField.text!.isEmpty)
{
var retVal = false
isUnique { (bool) in
retVal = bool
}
print("THIS IS THE RET VALUE: " + String(retVal))
//this print statement does not return the correct value
if retVal == false { return retVal }
}
errorLabel.text = " "
return true
}
As you can see, it doesn't work, I need to return bool in isUnique for my entire function.
You can't store the result of isUnique's closure then instantly return it, because isUnique will take as long as it takes to complete whatever task that is.
You want something like the following, where completion is called on all paths, but only once:
func validateFields(completion: (Bool) -> Void) {
//Other else if statements
//...
if ... {
/* ... */
} else if !(usernameTextField.text!.isEmpty) {
var retVal = false
isUnique { (bool) in
print("THIS IS THE RET VALUE: " + String(bool))
completion(bool)
}
} else {
errorLabel.text = " "
completion(true)
}
}
Caller:
validateFields { result in
print("result: \(result)")
}

I want to check the validation for both mobile number and email id in single textfield. How should I validate this?

I want to check the validation for both "Email id " and "mobile number" in single textfield. How should I validate the conditions for the same textfield?
Maybe this will help:
extension String {
var isPhoneNumber: Bool {
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count))
if let res = matches.first {
return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count
} else {
return false
}
} catch {
return false
}
}
}
extension String {
var isInt: Bool {
return Int(self) != nil
}
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailTest.evaluate(with: testStr)
}
if textField.text.characterCount > 6 {
if textField.text.isInt == true {
print("this might be users phone number"
} else if isValidEmail(testStr:textField.text) {
print("this might be users mail")
} else {
print("user entered wrong value or nothing")
}

Swift Using Contacts Framework, search using Identifier to match

Trying unsuccessfully to get a contact match providing contact Identifier. I desire to return contact, then to use the image associated with it. I am getting a nil match. thank you. This code I got from a demo, I'm kinda new to programming
import Contacts
var contact = CNContact()
var contactStore = CNContactStore()
let foundContact = getContactFromID("94AAD3B1-E9E1-48C9-A796-F7EC1014230A")
func getContactFromID(contactID: String) -> CNContact {
AppDelegate.getAppDelegate().requestForAccess { (accessGranted) -> Void in
if accessGranted {
let predicate = CNContact.predicateForContactsWithIdentifiers([contactID])
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey]
var contacts = [CNContact]()
var message: String!
let contactsStore = AppDelegate.getAppDelegate().contactStore
do {
contacts = try contactsStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keys)
if contacts.count == 0 {
message = "No contacts were found matching the given name."
}
}
catch {
message = "Unable to fetch contacts."
}
if message != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
Utility.showAlert(nil, message: message)
})
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.contact = contacts[0]
print("self.contact: \(self.contact)")
})
}
}
}
return self.contact
}
I solved it :), I removed the dispatch_async stuff, works now: here is fixed code.
func getContactFromID(contactID: String) -> CNContact {
AppDelegate.getAppDelegate().requestForAccess { (accessGranted) -> Void in
if accessGranted {
let predicate = CNContact.predicateForContactsWithIdentifiers([contactID])
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey]
var contacts = [CNContact]()
var message: String!
let contactsStore = AppDelegate.getAppDelegate().contactStore
do {
contacts = try contactsStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keys)
if contacts.count == 0 {
message = "No contacts were found matching the given name."
}
}
catch {
message = "Unable to fetch contacts."
}
self.contact = contacts[0]
}
}
return self.contact
}

Sorting mixed String-Int Strings numerically as the primary order, then alphabetically in swift

For a String which have both String and Int values (one of each) is it possible to do simple sort that will give the items ordered in numerical order as the primary order and alphabetical as the secondary order
var nameArray = ["Dave7", "Bob8", "Cathy9", "Henry10", "Susan10", "Pat11", "Steve12", "Dan12", "Ken1", "Sean2", "Howard3", "Dixie3", "Newman5", "Billy6"]
var sortedNameArray = nameArray.sort { $0.compare($1, options: .NumericSearch) == .OrderedAscending }
print(sortedNameArray) // gives the following:
Don't want this -> ["Billy6", "Bob8", "Cathy9", "Dan12", "Dave7", "Dixie3", "Henry10", "Howard3", "Ken1", "Newman5", "Pat11", "Sean2", "Steve12", "Susan10"]
Even though .NumericSearch was used the result is alphabetical.
I was able to get the desired result using a custom binary tree. Which gives the results:
Ken1 Sean2 Dixie3 Howard3 Newman5 Billy6 Dave7 Bob8 Cathy9 Henry10 Susan10 Pat11 Dan12 Steve12
But is there a simpler solution?
extension String {
var integerValue: Int? {
return Int(self)
}
}
func extractValueFromString(theString:String)->Int{
var catNumber: [Character] = []
//print("theString \(theString)")
for character in theString.characters{
var characterString = String(character)
if var value = characterString.integerValue { //if we don't check program crashes
//if numberSet.contains(Int(String(character))!) { //another way to check but redundant here
catNumber.append(character)
//print(catNumber)
// }
}
}
let numberString = String(catNumber)
return Int(numberString)!
}
class Node{
//nodes now only arrange strings
var data = ""
var value = Int()
var left:Node?;
var right:Node?;
deinit {
//print("deleting \(data)")
// print("node deleted")
}
init(data:String){
self.data = data;
//print(data)
}
}
class binaryTreeSort{
var root:Node?
init(){
}
deinit {
//print("tree deleted")
}
func getRoot()->Node{
return root!
}
func insertNewValue(data:String){
let newNode = Node(data:data)
var node:Node? = root
if (node == nil){
root = newNode
}
while (node != nil) {
let currentValue = node?.data
if currentValue == ""{
node?.data = data
return
}
if currentValue == data {
//we don't want duplicates.
return
}
if extractValueFromString(currentValue!) < extractValueFromString(data) {
if (node!.right != nil) {
node = node!.right
//print("Going Right at data \(node!.data)")
}else{
node!.right = newNode
//print("Going New Right at data \(node!.data)")
return
}
}else if extractValueFromString(currentValue!) == extractValueFromString(data){
if currentValue < data {
if (node!.right != nil) {
node = node!.right
//print("Going Right at data \(node!.data)")
}else{
node!.right = newNode
//print("Going New Right at data \(node!.data)")
return
}
}else{
if (node!.left != nil) {
//print("Going Left at data \(node!.data)")
node = node!.left
}else{
node!.left = newNode
//print("Going New Left at data \(node!.data)")
return
}
}
}
else{
if (node!.left != nil) {
//print("Going Left at data \(node!.data)")
node = node!.left
}else{
node!.left = newNode
//print("Going New Left at data \(node!.data)")
return
}
}
}
}
func inorderPrint(baseNode:Node){
if(baseNode.left != nil)
{
inorderPrint(baseNode.left!);
//print(" \(baseNode.data)")
}
print("\(baseNode.data)")
if(baseNode.right != nil)
{
inorderPrint(baseNode.right!)
//print(" \(baseNode.data)")
}
}
func reverseOrderPrint(baseNode:Node){
if(baseNode.right != nil)
{
reverseOrderPrint(baseNode.right!)
//print(" \(baseNode.data)")
}
print("\(baseNode.data)")
if(baseNode.left != nil)
{
reverseOrderPrint(baseNode.left!);
//print(" \(baseNode.data)")
}
}
}
var myBinaryTreeSort:binaryTreeSort? = binaryTreeSort()
for item in nameArray{
//print(item)
myBinaryTreeSort!.insertNewValue(item)
}
myBinaryTreeSort!.inorderPrint(myBinaryTreeSort!.getRoot())
print("---------------")
myBinaryTreeSort!.reverseOrderPrint(myBinaryTreeSort!.getRoot())
myBinaryTreeSort = nil //delete the tree
Use map to split the names into parts, sort to sort by number and name, and then map to restore the original:
func splitName(name:String) -> (String, Int) {
if let range = name.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet()) {
return (name[name.startIndex..<range.startIndex], Int(name[range.startIndex..<name.endIndex])!)
} else {
return (name, 0)
}
}
print(nameArray.map(splitName).sort({ lhs, rhs in
if lhs.1 < rhs.1 {
return true
} else if lhs.1 > rhs.1 {
return false
} else {
return lhs.0 < rhs.0
}
}).map({ "\($0.0)\($0.1)" }))
Some other ways it could be done would be to maintain element 0 of the tuple as the full name (with numbers) and then the final map just becomes map({ $0.0 }) Depending on sizes, this may be more optimal than splitting the name each time it's compared.
If you have an array, you can sort with a custom closure.
For example:
nameArray.sort({extractValueFromString($0) < extractValueFromString($1)})
Will get you close. You just need to check if they are equal and return $0 < $1 instead.
Here's how I solved this, doing something similar to what #Lou-Franco alluded to:
func endInteger(word: String) -> Int {
if let range = word.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet()){
let numberSubstring = word.substringFromIndex(range.startIndex)
return Int(numberSubstring) ?? 0
}
return 0
}
let sortedArray = yourArray.sort{endInteger($1) > endInteger($0)}

How to return from closure?

How can I return from closure in swift?
func closure(result: (Int -> Void)) {
var next = 1
while (true) {
result(next)
}
}
This is the invocation of the function
closure() { result in
// here I need to return
}
There is no return from the while loop in the question. In order to return there must be some conditional statement that will exit the while loop, something like:
while (true) {
result(next)
if something == false {
break;
}
}
or:
var i = 0
while (true) {
if i++ == 4 {
break;
}
print(i)
}
or:
var i = 0
while (i <
print(i)
}