Dictionary doesn't recognize key type (Updated) - ios

I have
func keyboardWillShow(aNotification: NSNotification) {
//Collect information about keyboard using its notification.
let info = aNotification.userInfo
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as NSValue) as Double
let curve : AnyObject? = info[UIKeyboardAnimationCurveUserInfoKey]
let kbFrame : AnyObject? = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
}
How can I get these to be read without the
"[NSObject : AnyObject]? does not have a member named 'subscript' " error?
In beta versions of xCode this had worked, but as of xCode 6.1 it no longer works properly.

userInfo is optional Dictionary, so you can use optional binding to unwrap value. And CGSize is a struct, not a object, so change AnyObject to CGSize.
if let info = aNotification.userInfo {
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as NSValue) as Double
let curve : AnyObject? = info[UIKeyboardAnimationCurveUserInfoKey]
let kbFrame: CGSize = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
}

Related

class_copyPropertyList not working in Swift 5. Whats the reason?

class_copyPropertyList is giving empty properties in Swift 5 and it was working correct in Swift 3
extension NSObject {
func toDictionary(from classType: NSObject.Type) -> [String: Any] {
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass = class_copyPropertyList(classType, &propertiesCount)
let propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
for i in 0 ..< Int(propertiesCount) {
let property = propertiesInAClass?[i]
let strKey = NSString(utf8String: property_getName(property)) as String?
if let key = strKey {
propertiesDictionary.setValue(self.value(forKey: key), forKey: key)
}
}
return propertiesDictionary as! [String : Any]
}
}
// call this for NSObject subclass
let product = Product()
let dict = product.toDictionary(from: Product.self)
print(dict)

Ambiguous use of 'subscript' and Cannot call value of non-function type 'AnyObject' errors retrieving data from Firebase in SWIFT 4.1

I'm changing the way I'm posting and retrieving firebase CLLocationCoordinated2D, from one post per value to one post with all values, so I found this post and I would like to implement it in my own code. Retrieving data from Firebase and storing as annotations on a map .
Im having the errors mentioned in the title on the constants date, time, latitude, longitude and desc.
I'm still learning Firebase so any explanation will be very helpful. Tis is the function where I get the errors.
func displayAnnotations() {
let ref = Database.database().reference()
ref.child("Sightings").observe(.childAdded, with: { (snapshot) in
let date = (snapshot.value as AnyObject?)!("Date") as! String?
let time = (snapshot.value as AnyObject)!("Time") as! String?
let latitude = (snapshot.value as AnyObject)!("Latitude") as! String?
let longitude = (snapshot.value as AnyObject?)!("Longitude") as! String?
let desc = (snapshot.value as AnyObject?)!("Description") as! String?
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
annotation.title = date
annotation.subtitle = time
self.mapView.addAnnotation(annotation)
})}
and this is the posting function:
func post() {
let date = dateLabel.text
let time = timeLabel.text
let latitude = latitudeLabel.text
let longitude = longitudeLabel.text
let sightingDescription = descriptionLabel.text
let post: [String:String] = ["Date" : date as AnyObject,
"Time" : time as AnyObject,
"Latitude" : latitude as AnyObject,
"Longitude" : longitude as AnyObject,
"Description" : sightingDescription as AnyObject]
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("Sightings").childByAutoId().setValue(post)
}
Is it just because it's written for a version previous to swift 4.1?
You changed [] to ()
let dic = snapshot.value as! [String:String]
let date = dic["Date"]
let time = dic["Time"]
let latitude = dic["Latitude"]
let longitude = dic["Longitude"]
let desc = dic["Description"]

How to know data coming from JSON is a Float or an Integer in Swift 3?

I am getting data from Json and displaying it in table view how to check whether the number is float or double or integer in swift 3 if it is float how to get the no.of digits after decimal can anyone help me how to implement this in swift 3 ?
if specialLoop.attributeCode == "special_price" {
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "$ \((arr.price))")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
let specialPrice = specialLoop.value.replacingOccurrences(of: ".0000", with: "0")
print(specialPrice)
cell.productPrice.text = "$ \(specialPrice)"
cell.specialPriceLabel.isHidden = false
cell.specialPriceLabel.attributedText = attributeString
break
}
else {
cell.specialPriceLabel.isHidden = true
let price = arr.price
print(price)
cell.productPrice.text = "$ \( (price))0"
}
You can use (if let)
let data = [String: Any]()
if let value = data["key"] as? Int {
} else if let value = data["key"] as? Float {
} else if let value = data["key"] as? Double {
}
as describe below, you can find a type of any object (whether custom class or built-in class like - String, Int, etc.).
class demo {
let a: String = ""
}
let demoObj = demo()
print(type(of: demoObj))
--> Output: "demo.Type"

Optional error while converting from Swift 2 to 3 in keyboardWillShow notification

I am converting my app to Swift 3 at the moment and I have problems with this function I used to show the keyboard before.
Initializer for conditional binding must have Optional type, not 'CGFloat'
The error appears in the third line.
It's been a while since I've programmed the last time and so I am not sure how to solve this.
func keyboardWillShow(_ sender: Notification) {
if let userInfo = sender.userInfo {
if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
let edgeInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
UIView.animate(withDuration: duration!, animations: { () -> Void in
self.tableView.contentInset = edgeInsets
self.tableView.scrollIndicatorInsets = edgeInsets
self.view.layoutIfNeeded()
})
}
}
}
This is one of those rare situations where I recommend force-unwrapping. You know the userInfo contains this information, and you are hosed if it doesn't. Moreover, there is no need to pass through AnyObject or to call cgRectValue; you can cast all the way down to a CGRect in a single move. So I would write:
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect).size.height
(Note that there is no if, because we are not doing a conditional binding; we simply cast, kaboom.)
[Note too that there is no need now to fetch the duration or to call animate or layoutIfNeeded; you can throw all of that away. We are already in an animation, and your changes to the contentInset and scrollIndicatorInsets will be animated in time to the keyboard.]
change
if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
to
if let foo = userInfo[UIKeyboardFrameEndUserInfoKey] {
let keyboardHeight = (foo as as AnyObject).cgRectValue.size.height
--- UPDATE ---
or
if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject?).cgRectValue.size.height {
AnyObject? works because AnyObject can contain Optional itself. So you have to casting to Optional explicitly. Either AnyObject? or Optional<AnyObject> will work.

DynamicProperty vs MutableProperty vs AnyProperty vs ConstantsProperty

What's difference between them? Could you give me an example of in which scenario I should use dynamic/mutable/any/constants property?
All your answer are in this link Property.swift
I give you some examples:
let privatString = MutableProperty<String>("PrivatString")
// AnyProperty are only for observing. You can't change it with observableProperty.value
let observableProperty: AnyProperty = AnyProperty<String>(privatString)
print(observableProperty)
// ConstantProperty describes observable constant value.
let constantProperty = ConstantProperty<String>("ConstantString")
// constantProperty.value = "" Error
// Thread safe observable mutable property. It's value is changable
let mutableProperty = MutableProperty<String>("mutableProperty")
mutableProperty.value = "New mutable property value"
// DynamicProperty uses KVO.
let dynamicProperty = DynamicProperty(object: self.view.layer, keyPath: "bounds")
dynamicProperty.producer.startWithNext { frame in
let frame = frame as! NSValue
let rect = frame.CGRectValue()
print(rect)
}

Resources