How to print a string from plist without Optional ?
One way to get rid of the Optional
is to use an exclamation point:
println(todayTitle!)
However, you should do it only if you are certain that the value is there. Another way is to unwrap and use a conditional, like this:
if let theTitle = todayTitle {
println(theTitle)
}
Paste this program into runswiftlang for a demo:
let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
println(theTitle)
}
Printing value of a optional variable includes the word Optional in Swift
Optional chaining is used here:
let age = self.clientDetail?.getAge()
So return of getAge()
is optional value. Try optional binding:
if let age = age {
println("age.....\(age)")
}
or simply unwrap the age
with age!
, but this will crash your app if age
is nil.
Swift Array is printing word optional from my array dont want to force unwrap
If you print out an optional, you will always have Optional(...)
in there. The only way to lose that is to unwrap. That's the only solution.
If you are worried about nil
values, check for nil
and then unwrap.
Xcode Swift how do I print a value form my custom plist file?
First of all please never use the NSArray/NSDictionary
related API in Swift to read a property list. You are throwing away the type information.
However you can read the values with
let array = NSArray(contentsOfFile: path!) as! [[String:Any]]
for item in array {
let name = item["name"] as! String
let active = item["active"] as! Bool
print(name, active)
}
The dedicated and recommended API is PropertyListSerialization
:
let url = Bundle.main.url(forResource: "test", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let array = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]]
A better way is the Codable
protocol and PropertyListDecoder
struct User : Decodable {
let name : String
let active : Bool
}
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "test", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let array = try! PropertyListDecoder().decode([User].self, from: data)
for item in array {
print(item.name, item.active)
}
}
The code must not crash. If it does you made a design mistake
Editor or way to print plist in a clean way without Xcode
There is a "Property List Editor" app as part of OS X (or there used to be, I'm away from my machine at the moment so can't check).
Failing that, you could write one in about half an hour!
indexPath.row printing optional text
Does this work?
print(the_object[indexPath.row].name)
I can't Unwrap a value from a plist key value
Depending on your style preference...
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
if let dict = nsDictionary {
let vTitle = dict["LbVacationsTitle"] as? String
if let vt = vTitle {
// ...
}
}
...or...
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
guard let dict = nsDictionary else {
print("Couldn't get a valid dictionary")
return
}
let vTitle = dict["LbVacationsTitle"] as? String
guard let vt = vTitle else {
print("Couldn't find a string matching LbVacationsTitle")
return
}
// ...
Related Topics
App Delegate Accessing Environment Object
How to Get Random Element from a Set in Swift
How to Detect Absent Network Connection When Setting Firestore Document
How to Rewrite Swift ++ Operator in : Ternary Operator
Firebase Observe Called After Following Command
Could Not Find an Overload for '/' That Accepts the Supplied Arguments
How to Update Text Using Timer in Swiftui
Swift - Seeding Arc4Random_Uniform? or Alternative
Trying to Stream Audio from Microphone to Another Phone via Multipeer Connectivity
"Unrecognized Selector Sent to Instance" in Swift
Parsing a Iso8601 String to Date in Swift
Why I Can Change/Reassigned a Constant Value That Instantiated from a Class
Format Realtime Stopwatch Timer to the Hundredth Using Swift
Storing/Passing Function Types from Swift Protocols
Swiftui: How to Present View When Clicking on a Button
Extend Existing Protocols to Implement Another Protocol with Default Implements
Swift: How to Create External Interface for Static Library (Public Headers Analog in Objective-C .H)