check if NSTextfield is empty or not OSX swift - swift

I am using a code to set value when user is not inputing a value to a NSTextfield, it does not continue after else if there is value in textfield
Here is an exampel.
func calculateAmountPanels(){
let fpanelsHigh = Float(panelsHigh)
let fpanelsWidth = Float(panelsWidth)
if panelsHighTextField != nil && panelsWideTextField != nil {
resHightLabel.stringValue = "N/A"
resWidthLabel.stringValue = "N/A"
lblScreenHight.stringValue = "N/A"
lblScreenWidth.stringValue = "N/A"
lblScreenArea.stringValue = "N/A"
lblAmountPanels.stringValue = "N/A"
}
else {
ammountPanels = (fpanelsWidth! * fpanelsHigh!)
printText()
}
}
Some advice would be appreciated since OSX coding seem to be different from ios.

I would add this extension:
extension NSTextField {
func setStringValueIfEmpty(newValue: String) {
if self.stringValue == nil || self.stringValue.isEmpty {
self.stringValue = newValue;
}
}
}
and call it on the fields, like so:
resHightLabel.setStringValueIfEmpty("N/A")

You have to check for the NSTextField's stringValue, e.g.:
panelsHighTextField.stringValue != nil
As HAS mentioned, you should also test for panelsHighTextField.stringValue.characters.count higher than 0.

Related

Confusion about setting a optional variable

I want to add the option for a user to add their phone number. If they add any phone number I want to add an alert informing them if they have not added a valid 10 digit phone number. However if they do not add anything in the phone number field I want the phoneInput variable to be set to "0". How would I go about doing this.
var phoneInput = ""
func signUp(){
if profileImage.image == nil {
showAvatarError()
} else if phoneNumber.text == "" {
self.phoneInput = "0"
} else if (phoneNumber.text?.characters.count)! != 10 {
showphoneNumberError()
}else if email.text == "" {
showEmailError()
}else if isValid(email.text!) != true{
showEmailError()
} else{
submitPressed()
print("Set info")
}
}
I'm not sure why you get the result that you do but here is a cleaner version
var phoneInput = ""
func signUp(){
// This check doesn't have anything to do with the number, so separe it
if profileImage.image == nil {
showAvatarError()
return
}
guard let temp = planEndValue.text else {
return
}
let userInput = temp.trimmingCharacters(in: .whitespaces)
if userInput.count == 0 {
self.phoneInput = "0"
} else if userInput.count != 10 {
showphoneNumberError()
}
}

guard statement variable do not give me value

var country = ""
if placemark.country != nil{
country = placemark.country!
}
self.awareLocationDetaile.text = country
Try to convert this code guard statement
guard let country = placemark.country else{
return
}
self.awareLocationDetaile.text = country
but unfortunate country have no value if i use guard statement where if give me value . what am i missing ?
UPDATE :
CLGeocoder().reverseGeocodeLocation(location) { ( clPlacemark :[CLPlacemark]?,error : NSError?) in
if error != nil {
print(error)
}else{
if let placemark = clPlacemark?[0]{
// print(placemark)
//MARK:- we are a good programmer
// var country = ""
// if placemark.country != nil{
// country = placemark.country!
// }
// self.awareLocationDetaile.text = country
guard let country = placemark.country else{
return
}
self.awareLocationDetaile.text = country
}
}
}
The guard statement works exactly as it is supposed to work. You are not missing anything. It does what it is supposed to do, not what you want. Your first code sample can be written a lot easier as
self.awareLocationDetaile.text = placemark.country ?? ""
It seems you copied a comment that the queen wrote after she wrote her very first line of code at the age of 89. Note the royal "we":
//MARK:- we are a good programmer
On the other hand, the return statement inside the guard statement will return from the closure, so nothing after that will be executed.

check if string contains anything outside of the character set swift

Hi I want to check if the user types in a string that contains anything outside of the character set (contains characters that are not specified in my set):
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-."
How can I achieve this? thanks in advance!
update
I tried using
var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")
if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location == NSNotFound){
println("No special characters")
}
but i'm getting a type 'range?' has no member 'location' error
You can use custom NSCharacterSet charactersInString and check if the character type is member of that invertedSet:
extension NSCharacterSet {
func characterInStringIsMember(aString: String) -> Bool {
var result = false
aString
.characters
.map{ UInt16(String($0).unicodeScalars.first?.value ?? 0) }
.forEach { result = characterIsMember($0) }
return result
}
}
let customCharSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-.").invertedSet
let stringTest = "abc"
if customCharSet.characterInStringIsMember(stringTest) {
print(true) //
} else {
print(false) // "false\n"
}
let stringTest2 = "abc%"
if customCharSet.characterInStringIsMember(stringTest2) {
print(true) // "true\n"
} else {
print(false)
}
Here is a simple solution, Just use NSCharacterSet like this :-
let name1="myname" // Input
let characterSet: NSMutableCharacterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("_-.")
name1.stringByTrimmingCharactersInSet(characterSet).isEmpty // If this return true, you enetered the right charcters

How can I check if a property has been set using Swift reflection?

Some of my models have optional properties. I'm trying to write a method that can evaluate if they've been set.
Below is an attempt, but I can't figure out how to determine a nil value from an Any object [edit: (the child variable is of type Any)]. It doesn't compile.
func allPropertiesHaveValues(obj: AnyObject) -> Bool {
let mirror = Mirror(reflecting: obj)
for child in mirror.children {
let value = child.value
if let optionalValue = value as? AnyObject? { //Does not compile
if optionalValue == nil {
return false
}
}
}
return true
}
Edit:
I forgot to clarify that the child value in the above example is always of type Any. The Any type is difficult in that it cannot be compared to nil and a cast to AnyObject always fails. I've tried to illustrate it in the playground below.
var anyArray = [Any]();
var optionalStringWithValue: String? = "foo";
anyArray.append(optionalStringWithValue);
var nilOptional: String?
anyArray.append(nilOptional)
print(anyArray[0]); // "Optional("foo")\n"
print(anyArray[1]); // "nil\n"
if let optionalString = anyArray[0] as? AnyObject {
//will always fail
print("success")
}
//if anyArray[1] == nil { // will not compile
//}
I used #ebluehands technique of reflecting the Any value to modify the original function. It cycles through the properties with an initial mirror, then reflects each one individually using displayStyle to determine if the property is optional.
func allPropertiesHaveValues(obj: AnyObject) -> Bool {
let mirror = Mirror(reflecting: obj)
for child in mirror.children {
let value: Any = child.value
let subMirror = Mirror(reflecting: value)
if subMirror.displayStyle == .Optional {
if subMirror.children.count == 0 {
return false
}
}
}
return true
}
Obsolete:
You can simply check if the optional value is nil or not :
func allPropertiesHaveValues(obj: AnyObject) -> Bool {
let mirror = Mirror(reflecting: obj)
for child in mirror.children {
//child.value being an optional
if child.value == nil {
return false
}
}
return true
}
Edit:
To check if an Any object is optional and contains a value or not using reflection :
let optionalString : String? = "optional string"
let any : Any = optionalString
//First you will need to create a mirror of the any object
let mirror = Mirror(reflecting : any)
//Then you can check the display style to see if it's an optional
if mirror.displayStyle == .Optional {
//If it is, check the count of its children to see if there is a value or not
if mirror.children.count == 0 {
print("I don't have a value")
}
else {
print("I have a value")
}
}
Here is a playground example (based on yours):
var anyArray = [Any]()
var optionalStringWithValue: String? = "foo"
anyArray.append(optionalStringWithValue)
var nilOptional: String?
anyArray.append(nilOptional)
let string = "string not optional"
anyArray.append(string)
print(anyArray[0]) // "Optional("foo")\n"
print(anyArray[1]) // "nil\n"
print(anyArray[2]) // "string not optional\n"
let mirrorOptionalWithValue = Mirror(reflecting: anyArray[0])
if mirrorOptionalWithValue.displayStyle == .Optional
&& mirrorOptionalWithValue.children.count == 1 {
print("Is an optional and contains a value")
}
let mirrorOptionalWithoutValue = Mirror(reflecting: anyArray[1])
if mirrorOptionalWithoutValue.displayStyle == .Optional &&
mirrorOptionalWithoutValue.children.count == 0 {
print("Is an optional but is nil")
}
let mirrorNotAnOptional = Mirror(reflecting: anyArray[2])
if mirrorNotAnOptional.displayStyle != .Optional {
print("Is not an optional")
}
Another option is create a extension.
extension NSManagedObject {
func checkIfAllRequiredMembersAreSet() -> Bool {
let attributes = self.entity.attributesByName
for (attribute, value) in attributes {
if value.attributeValueClassName != nil {
let v: AnyObject? = self.valueForKey(attribute)
if !value.optional && v != nil {
return false
}
}
}
return true
}
}
Based on this answer, I recommend using if case Optional<Any>.some(_).
I did something recently to make sure I have at least one optional set. Here's an example to make sure all are set. You can paste into playgrounds:
import Foundation
struct SomeError: Error {
let code: Int?
let message: String?
let errorDescription: String?
var allValuesSet: Bool {
for aChild in Mirror(reflecting: self).children {
if case Optional<Any>.some(_) = aChild.value {
continue
} else {
return false
}
}
return true
}
}
let errorTest = SomeError(code: nil, message: "failed", errorDescription: nil)
let errorTest2 = SomeError(code: -1, message: "failed", errorDescription: "missing information")
print("is valid: \(errorTest.allValuesSet)") //is valid: false
print("is valid: \(errorTest2.allValuesSet)") //is valid: true

swift ? must be followed by a call, member lookup, or subscript

I think I'm looking at some outdated code:
#IBAction func stockLevelDidChange(sender: AnyObject) {
if var currentCell = sender as? UIView {
while (true) {
currentCell = currentCell.superview!;
if let cell = currentCell as? ProductTableCell {
if let id = cell.productId? {
var newStockLevel:Int?;
if let stepper = sender as? UIStepper {
newStockLevel = Int(stepper.value);
}
else if let textfield = sender as? UITextField {
if let newValue = textfield.text.toInt()? {
newStockLevel = newValue;
}
}
if let level = newStockLevel {
products[id].4 = level;
cell.stockStepper.value = Double(level);
cell.stockField.text = String(level);
}
}
break;
}
}
displayStockTotal();
}
}
But in the first line of the function I get " '?' must be followed by a call, member lookup, or subscript" (for the question mark after as)
What does this error mean and how does this code change for Swift 1.2?
Actually the as? are all fine. The problem is this line:
if let id = cell.productId?
Just remove the question mark at the end of that. It makes no sense.
In 1.2, toInt is gone. So,
if let newValue = textfield.text.toInt()?
Should be replaced with:
if let newValue:Int? = Int(textField.text!)
The problem is the if let newValue = textfield.text.toInt()? { .. If toInt() returns an Int? then just get rid of the ? there.