FAQ Database Discussion Community


Facebook graph object/entity parsing SDK 4 in Swift

ios,facebook,swift,facebook-graph-api,optional
In Swift how do you parse the result of a fbk graph request? I have a nested dictionary and casting to [String: String] does not work. I have casted to NSDictionary which works for level 1 but anything nested started complaining about optionals and casting. I see from the changeling...

How to create Non-optional stored properties for UIViewController Custom Subclass

swift,optional
When subclassing UIViewController ( and other similar classes ) we do not have to deal with any initialization, so if I create a stored property that is not an optional, Xcode will complain that there are no initializer. So how can I create a non-optional store property in these classes?...

Swift: call methods of an optional variable

swift,optional,questionmark
So I know the difference between '!' and '?', I just want to know what is the best way to use them when calling a method of an optional variable var bar: Bar? = nil bar?.doSomething() // this will be valid, but wouldn't call doSomething bar!.doSomething() // Given error: EXC_BAD_INSTRUCTIONS...

How can I write safe java.util.Optional null pointer assignment when getting aList.get(0)?

java-8,optional
I have the following code that throws when my call to .getList().get(0) is null. Optional<MyObject> _obj = java.util.Optional.ofNullable(objParam); // where getListOfMyObjects() returns List<MyObjects> Optional<String> desc = Optional.ofNullable(_obj.get().getMyParentObject().getListOfMyObjects().get(0).getDesc()); How can I write safe java 8 Optional code (use .map, etc,.) that will prevent .getList().get(0) from throwing?...

Scala Option type upper bound don't understand

scala,optional,type-systems
I'm reading Functional Programming in Scala, and in chapter 04 the authors implement Option on their own. Now, when defining the function getOrElse they use an upper bound to restrict the type of A to a supertype (if a understood correctly) So, the definition goes: sealed trait Option[+A] { def...

Optional vs throwing an exception

java,java-8,optional
Is it true that since Java 1.8 returning Optional object is more preferable than throwing an exception? Increasingly i see the code like this: public Optional<?> get(int i){ // do somtething Object result = ... Optional.ofNullable(result); } Instead of this: public Object get(int i){ if(i<0 || i>=size) { throw new...

Did boost::optional's implicit cast to bool go away?

c++,boost,optional
I started porting a vc++10/boost 1.48 codebase to vc++12/boost 1.57 and I'm getting an error that boost::optional can't convert to bool. I thought this was a feature of boost::optional, did it get removed? Example: bool fizz(){ boost::optional<int32_t> buzz; return buzz; } gives Error 21 error C2440: 'return' : cannot convert...

Swift Optionals vs. Ruby ||=

ruby,variables,swift,optional
I'm making the transition from learning Ruby to Swift and trying to make any useful associations in order to get a better understanding of similar concepts from both programming languages. I noticed in Swift there are optionals which either have or don't have a value assigned to variables. var optinalString:...

How to port from java.util.Optional method call chaining to Guava Optional?

java,java-8,guava,optional
I have the following that uses java.util.optional // this works fine for java.util.Optional Optional <Context> xx = Optional.ofNullable(x); Optional<DateRange> dates = xx.map(Context::getEntity).map(Entitiy::getDates); However, I need to convert that to use guava's optional. I tried something like guava Optional transform but I'm unsure how to chain something like this with guava...

Convert list of Option to list of T when T cannot be copied

iterator,rust,optional
How do I take a Vec<Option<T>>, where T cannot be copied and unwrap all the Some values? I run in to the error cannot move out of borrowed content when in the map step. I'm happy to move ownership of the original list and "throw away" the Nones. #[derive(Debug)] struct...

Swift unit test - unexpectedly found nil while unwrapping an Optional value

ios,swift,unit-testing,optional
I am trying to write a unit test which is resulting in this error fatal error: unexpectedly found nil while unwrapping an Optional value When I run my tests normally (Command-U) then it fails on this line in my ViewController (outside of my tests) songTitleTextField.placeholder = "Enter your song title...

Fortran Functions with optional arguments

function,fortran,optional
I want to use an operator .ef. however the operator does not accept optional arguments. Is it possible to keep the my function and be able to have the operator working too? Module Core Implicit None Interface Operator (.ef.) Module Procedure fes End Interface Operator (.ef.) Contains Function fes &...

Scala fold evaluate function ifEmpty instead of expression

scala,optional,fold
If I have an Option: val o = someFuncReturningOption() and I chose to fold: o.fold(valIfEmpty){(_, i) => println(i) } Is there a variant of fold or another function that takes a function instead of a value for ifEmpty such that the function is only evaluated if the (in this case)...

'Cannot convert the expression's type' with optional in closure body

swift,closures,optional
I have come across (most definitely) a feature that I don't quite understand. I have a closure, that takes in a Float and has no return value, aka (number: Float) -> Void. In that closure, I perform a call on optional value, not forcing its unwrapping, because I like the...

array created with optional

ios,swift,optional
I am declaring a array: var array:[String] = [] assigning values: array.append(uniqueId as String) and then pass it to a function: static var levels_array : [String] = [] class func setLevelsArray(arr:[String]) { GamePrefrences.levels_array = arr println(GamePrefrences.levels_array) } My problem is that when i print the array i get: [Optional(88868658), Optional(112051080),...

Cached Optional values

java,boolean,java-8,optional
There doesn't seem to be any cached objects of type Optional<Boolean> for the true and false values available in the standard library. Am I missing them somewhere? It would surprise me if there were no such objects because it seems to me like this would be so useful, for both...

How to wrap a method that returns an optional with fromNullable?

java-8,guava,optional
I have a method that I don't own that is returning null but return type is Optional<Boolean>. When I call x.IsPresent() it throws (scenario #2). I tried wrapping the method in a fromNullable but I get a type mismatch (screen shot below). How can I fix so IsPresent() doesn't throw?...

Why is main window of type double optional?

ios,swift,optional,uiwindow
When accessing UIapplication's main window it is returned as a UIWindow?? let view = UIApplication.sharedApplication().delegate?.window // view:UIWindow?? Why is it returning as a double optional and what does it mean and if put into a if let should I add one ! after it? if let view = UIApplication.sharedApplication().delegate?.window! My...

Multiple unwrap of optionals

swift,optional,unwrap
I have an object, let's say its called "Event". Event has several optionals. struct Event { var name: String! var location: String? var attendees: [String]? var dresscode: String? var startDate: NSDate! var endDate: NSDate? var description: String { return "Name: \(name). Location: \(location). Attendees: \(attendees). Dresscode: \(dresscode). Start date: \(startDate)....

How do you inspect an Optional-String's length?

string,swift,optional
class PersonEntry: NSObject { var firstName: String? var lastName: String? } //This errors if (self.person.firstName?.isEmpty) { println("Empty") } //Compiler auto-correction is this if ((self.model.firstName?.isEmpty) != nil) { println("Empty") } I understand that optional chaining returns an optional type. So I suppose my question is, how do you unwrap an optional...

Optional chaining not working for optional protocol requirements

ios,swift,optional
I'm following this example from Apple and the optional chaining does not work as expected. There is a protocol with optional property and function: @objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } A class that conform to above protocol: class...

Grails service fails working with Optional class

java,grails,model-view-controller,groovy,optional
I've tried to use Optionals in grails service, but whenever I do, I get HTTP Status 500 - Error applying layout : main and a bunch of stack traces, which looks to me like nothing but framework gizmos. But when I try the same code in controller, it works ok....

Swift Optional of Optional

ios,swift,optional
For a project of mine, I have to create a proxy AppDelegate that will forward calls to a another AppDelegate. UIApplicationDelegate havs a var window: UIWindow?. My question is, why can't I do this: private lazy var realAppDelegate: UIApplicationDelegate = { return AppDelegate() }() var window: UIWindow? { get {...

OrElseGet chaining in Java8

lambda,java-8,optional
I have a list in which 50 values are coming. Now I have 3 matching conditions, however matching conditions have some order. Like for P1 condition I have to match first, if it does not matches in any element then second condition should be evaluated for logic and so on....

experimental::optional nullopt_t constructor

c++,optional,c++1z
Here is described the nullopt_t and nullopt for the optional object proposed for c++: struct nullopt_t{see below}; constexpr nullopt_t nullopt(unspecified); [...] Type nullopt_t shall not have a default constructor. It shall be a literal type. Constant nullopt shall be initialized with an argument of literal type. The reason for this...

How to use optional unwrapping and a boolean condition in a single if condition

swift,boolean,optional
I want to check whether an object is type of NSNumber and a boolean variable is true or not in a single statement. For this I wrote as below: let someBool = ... if value.isKindOfClass(NSDictionary) { // do something with dict } else if (let number = value as? NSNumber)...

How to convert Optional Double to Double in javafx

javafx,optional
The following code if compiled gives the following error. How to solve this error: incompatible types: OptionalDouble cannot be converted to Double .average(); Double todaypctpnl = openPositionsdata.stream() .mapToDouble(c->Double.parseDouble(c.getTodaypctpnl())) .average(); ...

what is happening behind the scenes in optional if statements in swift

swift,optional
accodring to apple documentation the following code checks if convertedNumber has been initialized, and if so, it executes the if block. let convertedNumber: Int? if convertedNumber { //do stuff } I'm interested in what's happening behind the scenes. Is this some sort of shorthand notation, because the condition in if...

Optionals in Swift, why this simple code doesn't print optional?

ios,swift,optional,swift-playground
var shoppingList = ["item1": "bread", "item2": "milk" ] if let oldItem = shoppingList.updateValue("honey", forKey: "item2") { println("old value was \(oldItem)") } // This prints out "old value was milk" However, if I do this var shoppingList = ["item1": "bread", "item2": "milk" ] let oldItem = shoppingList.updateValue("honey", forKey: "item2") println("old value...

Why is a Swift implicitly unwrapped optional `nil`?

swift,optional
self.presentTextInputControllerWithSuggestions(nil, allowedInputMode: WKTextInputMode.Plain) { (results:[AnyObject]!) -> Void in // results can be nil if let speech = results.first as? String { debugPrint(speech) } } Excuse my ignorance, I'm afraid I've missed some basic understanding of optionals. I'm under the impression that !, the implictly unwrapped optional indicator, is a guarantee...

if-let statement doesn't unwrap optional

ios,swift,optional
I've run across something in my code that seems curious and was wondering if there is a straightforward explanation for this behavior. Given the following statement: if let tabBarController = topViewController as? UITabBarController { for subcontroller in tabBarController.viewControllers! { println(subcontroller.view) if let subcontrollerView = subcontroller.view { println(subcontrollerView) println(subcontrollerView!) if subcontrollerView!.window...

Scala: Access optional value in optional object

scala,error-handling,optional,forced-unwrapping,unwrap
Is there a good way to access a Option Value inside a Option Object? The nested match cases result in a ugly tree structure. So if I have for example: case class MyObject(value: Option[Int]) val optionObject : Option[MyObject] = Some(MyObject(Some(2)) The only way I know to access the value would...

Swift optional values during initialization preventing default initializer inheritance

swift,initialization,constants,optional,swift-playground
In Swift: 1) If you provide a default value for all of the stored properties in a class, then you inherit the default initializer, ie - init(). -- AND -- 2) A property of any optional type defaults to the value of nil, ie - var shouldBeNill: String? //should initially...

How to pass an optional value to objecive c class from swift

objective-c,swift,optional
Below is my code var img = self.appDelegate.loadImageFromCache(imageURL)! if (img != nil) { cell.imageArray.append(img!) } Even if the img object is available I'm getting error as "fatal error: unexpectedly found nil while unwrapping an Optional value" My cell class is an objective c class and the imageArray is a property....

Is it a good practice to use Optional as an attribute in a class? [duplicate]

java,java-8,optional
This question already has an answer here: Uses for Java8 Optional 8 answers Guava Optional as method argument for optional parameters 1 answer I have read something about the purpose of Optional (unfortunately I don't remember where) in Java 8, and I was surprised the writer didn't mention the...

Idiomatic Scala for Options in place of if/else/else chain

scala,coding-style,optional
I often find myself writing Scala of the form: def foo = { f1() match { case Some(x1) => x1 case _ => f2() match { case Some(x2) => x2 case _ => f3() match { case Some(x3) => x3 case _ => f4() } } } } This is...

Optional.ifAbsentThrow()?

java-8,optional,java-stream
Suppose I need to find a value of a certain order, then get its id, and then its localized-id. And if I can't do it, I want to throw and exception: return values.stream() .filter(value -> value.getOrder("order") == order) .findAny() .map(Attribute::getId) .map(Id::getLocalizedId) .orElseThrow(() -> new RuntimeException("Could not get the localized id...

Using Java 8 Optional with JSONObject?

json,java-8,optional,jsonobject
GIVEN: JSONObject o = <populated from json source>; if (o.has("stuff") && response.getJSONObject("stuff").has("stuffList") && o.getJSONObject("stuff").getJSONArray("stuffList").size() > 0) { doStuff() } ASK: How can I rewrite the above using java.util.Optional so that I don't have to make all those JSONObject checks? Something like: java.util.Optional<JSONObject> _O = java.util.Optional.ofNullable(o); java.util.Optional<Integer> size = _response.map(JSONObject::getJSONObject("stuffList")...<etc>???;...

Issues setting string to optional value

ios,swift,optional
how can i pass the label inside the button to the next activity, here is my code but it doesn't work @IBOutlet weak var elecB: UIButton! my prepareForSegue code override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var result:searchResultView = segue.destinationViewController as! searchResultView if elecB.selected{ result.cat = elecB.titleLabel?.text! } } it...

Create an optional tuple

c++,boost,tuples,variadic-templates,optional
I don't understand why there is no optional tuple, and I mean by that, something like this ; optional<int,string,char> that would combine an optional int, optional string and optional char. You can think of it like an optimized std::tuple<boost::optional<T>...> where the booleans used by the optionals would be all together...

Mockito error with method that returns Optional

java,mockito,optional
I have an interface with the following method public interface IRemoteStore { <T> Optional<T> get(String cacheName, String key, String ... rest); } The instance of the class implementing the interface is called remoteStore. When I mock this with mockito and use the method when: Mockito.when(remoteStore.get("a", "b").thenReturn("lol"); I get the error:...

Fatal error when unwrapping CLLocation Location Coordinate

ios,iphone,swift,ios8,optional
I currently have a test application to teach myself Core Location. It is an app with a button which will either show your location when you press a button, or an alert when location services are off. I get a fatal error (unexpectedly found nil when unwrapping option value) When...

Swift 1.2 Results to '?' must be followed by a call, member lookup, or subscript [duplicate]

ios,swift,optional
This question already has an answer here: swift ? must be followed by a call, member lookup, or subscript 2 answers Updating to Swift 1.2 / Xcode 6.3 caused the following errors: Could someone with understanding of changes that took place between 1.1 and 1.2 help out what's going...

How to use swift flatMap to filter out optionals from an array

swift,functional-programming,optional,higher-order-functions,flatmap
I'm a little confused around flatMap (added to Swift 1.2) Say I have an array of some optional type e.g. let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5] In Swift 1.1 I'd do a filter followed by a map like this: let filtermap = possibles.filter({ return $0...

Implicitly Unwrapped Optionals in Swift does not seem to work

ios,xcode,swift,optional
I am following the The Swift Programming Language book to investigate strong reference cycle. One of the examples that should be working cannot be compiled in Xcode. I don't understand why the code is broken. On this chapter, there is an example that looks like this: When I try to...

Unwrapping optional Value

swift,optional
I am trying to parse through an optional value that has these values in it Optional(UITableViewCell: ox7ff2f9cfbc80; frame = (0 0; 414 44); text = 'Clarity'; autoresize = W; layer = <CALayer:0x7ff2f9cfb250>>) and would like to just grab the text part of 'Clarity' to print out in another line. Please...

Java 8 Optional.ifPresent is my code wrong or is it eclipse?

eclipse,java-8,nullable,optional
I am new to Java 8 and trying out Null type annotations and Optional. For my example below, I have used String rather than my class and am calling toUpperCase just to call something, in my case I actually call a function passing in a parameter (so don't think I...

How can I map an optional into a primitive optional?

java,lambda,optional
I know I can map an Optional into an another wrapper type optional. Optional<Long> millis(Date date) { return ofNullable(date).map(Date::getTime); } How can I map or flatMap into an OptionalLong? OptionalLong millis(Date date) { } I tried but had no luck. ofNullable(value).flatMap(v -> { // javac has never liked me return...

How do I convert a optional NSInteger to a non-optional one?

swift,optional
I need to retrieve a setting (with Swift): var highScoreNumber: NSInteger = 0 var returnValue: [NSInteger]? = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [NSInteger] if (returnValue != nil) { highScoreNumber = returnValue as NSInteger } I tried this and other variations of the code and I always get 'NSInteger?' not convertible to 'NSInteger' This...

Java 8 generic collections with optionals

java,generics,java-8,optional,bounded-wildcard
I have a relatively simple looking problem that I am trying to solve. There doesn't seem to be an intuitive way to do this or, I am missing something here. Consider this method to find the main image and if none exists, return first image- public Image findMainImage(Collection<? extends Image>...

Swift: why do I need optionals anyways?

ios,swift,optional
I've read a few articles about it and understand the basic principle and do agree that it could be useful in some cases. However, most of the time I would want my program to crash if I was getting nil somewhere that I shouldn't be -- that's how'd I know...

Guarantee not optional value, while allowing optional value as setter

swift,setter,getter,optional
class MyClass { private var _image: UIImage var image: UIImage { set { if newValue == nil { _image = UIImage(named: "some_image")! } } get { return _image } } } My goal is to guarantee non-optional value when image is accessed Can i achieve this without additional function? Even...

Whose view is not in the window hierarchy? Swift

ios,swift,optional
I want a table view controller to be displayed. Therefore I present the view controller in the completionwithitemshandler property below. let activityViewController = UIActivityViewController(activityItems:[memeedimage] , applicationActivities: nil) presentViewController(activityViewController, animated: true, completion: nil) activityViewController.completionWithItemsHandler = { (activity, success, returneditems, error) in println("Activity: \(activity) Success: \(success) Items: \(returneditems) Error: \(error)") self.save()...

How do I represent an Optional String in Go?

string,go,null,optional,variant
I wish to model a value which can have two possible forms: absent, or a string. The natural way to do this is with Maybe String, or Optional<String>, or string option, etc. However, Go does not have variant types like this. I then thought, following Java, C, etc., that the...

Optional<> and return type narrowing

java,optional,narrowing
In Java < 8, returning "unsafe" objects (objects or null), I was able to specialize return type in subclass: class A {} class B extends A {} interface Sup { A a(); /* returns A instance, or null */ } interface Sub extends Sup { B a(); } In Java...

accessing nested dictionary from api in swift

swift,optional
Holy cow...there MUST be a better way to access formatted in floorplan_summary: { bedrooms: { low: 1, high: 2, formatted: "1 - 2 Beds" } } than doing this: if data["floorplan_summary"]?["bedrooms"] != nil { let bedrooms = data["floorplan_summary"]?["bedrooms"] as NSDictionary if bedrooms["formatted"] != nil{ self.beds = bedrooms["formatted"] as String }...

defining functions with optional arguments

python,function,optional,def
Hi I'm trying to understand how to implement optional arguments in a python function. For example, in the basic function below def Ham(p,*q): if q: print p+q else: print p Ham(2) Ham(2,3) I expect Ham(2) to return '2' which it does, however Ham(2,3) gives an error. EDIT: Many thanks. Many...

Unwrapping Swift optional without variable reassignment

swift,optional
When using optional binding to unwrap a single method call (or optional chaining for a long method call chain), the syntax is clear and understandable: if let childTitle = theItem.getChildItem()?.getTitle() { ... } But, when provided the variable as a parameter, I find myself either using: func someFunction(childTitle: String?) {...

Java Optional for method argument?

java,java-8,guava,optional
I was reading this post on using Optionals for method arguments and the consensus seems to be to never use them for that purpose. Guava Optional as method argument for optional parameters But are there exceptions to this rule at all on the API side (not application side)? I can't...

Boolean Predicate (guard) in Java Optional

haskell,java-8,optional
Here's the method I have. public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { if (isInRoutesFile(element)) { return controllerName(element) .flatMap(name -> findController(element.getProject(), name)) .map(controller -> new PsiReference[]{new RPsiElementReference(controller)}) .orElse(new PsiReference[0]); } return new PsiReference[0]; } Now, I'd like to avoid the if clause and somehow built the predicate into the...

Optional chaining for constructor calls?

swift,optional,optional-chaining
I want to optionally cast an NSNumber? to an Int?, but the initialiser method for Int only takes init(NSNumber), so I can't pass an NSNumber?. Is there a way for me to compact this code so that it uses something like optional chaining? // number: NSNumber? let integer = number...

Segmentation fault on enum

swift,enums,optional
When checking an enum value with an optional value, I get a segmentation fault. This is wrong: message?.type == .In and this is right: message!.type == .In // after checking for nil of course What is happening?...

Weird “fatal error: unexpectedly found nil while unwrapping an Optional value”

ios,swift,optional,unwrap
I have 6x UIImageView in my ViewController. I also have tap gestures assigned to them. When the user taps an image, segue is performed. I add those ImageViews to array and that's where an app crashes: @IBOutlet weak var p0: UIImageView! @IBOutlet weak var p1: UIImageView! @IBOutlet weak var p2:...

fatal error: unexpectedly found nil while unwrapping an Optional value with toInt()

swift,optional
I am getting the error that is in the title, when I run my code. The main problem occurs in the code below. I don't really understand what is going on. I started (and completed) this project to make a bingo tracker in swift during the beta, but apparently the...

How to return from ifpresent in java8 for Optional null pointer checks?

java,nullpointerexception,optional
I have this unsafe code that could throw nullPtr exceptions: Type t = objParam.getProject().getType(); How can I use java 8 optional and ifpresent()to return the least amount of code safely (one liner)? // How can I modify this to return from the ifPresent()...or a better way in // java8? how...

Swift Optionals(?). What's the difference between two?

swift,syntax,nil,optional-parameters,optional
In terms of the optionals(?), what's the difference between the two? I'm trying to pick up swift and it seems that the location of "?" matters and i'm having a hard time grasping the effect of having "?" in different places. var beaconGroup:GroupData = filteredArray.firstObject? as GroupData var beaconGroup:GroupData =...

Difference between optional and forced unwrapping

swift,optional,forced-unwrapping
Below is the code for optional string for variable name yourname and yourname2. Practically what is difference between them and how forced unwrapping in case of yourname2 var yourname:String? yourname = "Paula" if yourname != nil { println("Your name is \(yourname)") } var yourname2:String! yourname2 = "John" if yourname2 !=...

How to convert single element list to java 8 optional

java,collections,java-8,optional
How to nicely convert list containing one or zero elements to Optional? The ugly code: List<Integer> integers = new ArrayList<>(); Optional<Integer> optional = integers.size() == 0 ? Optional.empty() : Optional.of(integers.get(0)); ...

Regex optional capturing group?

regex,optional,capturing-group
After hours of searching I decided to ask this question. Why this regular expression: ^(dog).+?(cat)? doesn't work as I think it should work (capture the first dog and cat if there is any)? What am I missing here? dog, cat dog, dog, cat dog, dog, dog ...

What's the meaning of as!,init? in swift?

swift,optional
Sometime when I use "as" ,xcode prompts failed and suggests change to "as!".Also I see some construstors is "init?".I know some variables could be difined as optional.What the meaning of a constructor to be optionsal? I looked up the questions in "the swift programming language",but failed to get the answer....

So if string is not NilLiteralConvertible… what do some string functions return?

ios,swift,optional
Let's assume the following code: let url = "http://%20abc" let urlString = url.stringByRemovingPercentEncoding! if urlString != nil { println("done") } stringByRemovingPercentEncoding should return an optional String. So let's unwrap it. Now what happens when it actually 'fails' and doesn't return a string? String is not a NilLiteralConvertible, therefore there is...

Equivalent in java 8 from guava Enums.getIfPresent() that will return java.util.Optional?

java-8,guava,optional
I have the following code from an old group that is using guava Optional and Enums (getIfPresent). // getNameAsString returns the string literal but I want to safely convert // to an enum and return an java.util.Optional <MessageName>. // MessageName is an enum Optional<MessageName> msgName = Enums.getIfPresent(MessageName.class, obj.getMessage().getNameAsString()); How can...

Chaining Optionals in Java 8

java,lambda,java-8,optional
Looking for a way to chain optionals so that the first one that is present is returned. If none are present Optional.empty() should be returned. Assuming I have several methods like this: Optional<String> find1() I'm trying to chain them: Optional<String> result = find1().orElse( this::find2 ).orElse( this::find3 ); but of course...

NSUserDefaults properly storing Strings in SpriteKit Swift

ios,string,swift,nsuserdefaults,optional
So I set up a NSUserDefault to store a string in my GameViewController NSUserDefaults.standardUserDefaults().setObject("_1", forKey: "SkinSuffix") The idea is it stores a suffix which I will attach to the end of an image name in order to save what skin of a character the player should use. When I call...

Why to have forced downcasting in UITableViewCell?

ios,uitableview,swift,optional
I am trying to connect two different scenarios to learn about downcasting. First Scenarios: let x: AnyObject? = 10 let z = x as Int In this case i am able to downcast AnyObject? using as. Now lets check another Scenarios Second Scenario here i have a method tableView.dequeueReusableCellWithIdentifier("Cell") Since...

Why are multiple unwrapping optionals impossible?

swift,if-statement,optional
I've been playing with optionals in swift. I make frequent use of the conditional unwrap pattern: var myOptional: AnyObject? if let unwrapped = myOptional { // do stuff } However, on occasion I have two optional values that I only want to use if both of them are non-nil. As...

!? Strange double unwrapped optional syntax in for_in []?

swift,syntax,optional
Earlier I had a question that I figured out, but the answer led to another question. What is the !? syntax, I haven't seen it anywhere else, but it was the only way I could get the code to compile. Can someone tell me what "!?" the syntax means? Is...