optional

How do I unwrap an Optional when pattern matching tuples in Swift?

本小妞迷上赌 提交于 2019-12-18 08:10:13
问题 In Swift, there's a common if let pattern used to unwrap optionals: if let value = optional { print("value is now unwrapped: \(value)") } I'm currently doing this kind of pattern matching, but with tuples in a switch case, where both params are optionals: //url is optional here switch (year, url) { case (1990...2015, let unwrappedUrl): print("Current year is \(year), go to: \(unwrappedUrl)") } However, this prints: "Current year is 2000, go to Optional(www.google.com)" Is there a way I can

Appending tuples to an array of tuples

风格不统一 提交于 2019-12-18 07:14:05
问题 My class declares an array var laps: (start: NSDate!, end: NSDate!)[] = [] When a tuple is added to this array I'd like to be able to do something like let now = NSDate() var lap = (now, nil) laps.append(lap) But at the append I get the error Missing argument for parameter 'end' in call . 回答1: I've tried to following, and it looked correct syntactically: typealias MyTuple = (start: NSDate!, end: NSDate?) then in the method, I did: var laps: Array<MyTuple> = Array() laps.append((NSDate.date(),

Concatenate two or more optional string in Java 8

不问归期 提交于 2019-12-18 06:13:16
问题 I have a rather simple question for you guys. In Java 8 it was introduced the Optional type. I have two objects of type Optional<String> and I want to know which is the more elegant way to concatenate them. Optional<String> first = Optional.ofNullable(/* Some string */); Optional<String> second = Optional.ofNullable(/* Some other string */); Optional<String> result = /* Some fancy function that concats first and second */; In detail, if one of the two original Optional<String> objects was

Variable 'xxx' was never mutated, consider changing to 'let'

╄→гoц情女王★ 提交于 2019-12-18 04:34:23
问题 Updated to xcode7-beta I run across a new kind of warning. Here is my code override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes: [UICollectionViewLayoutAttributes]? = super.layoutAttributesForElementsInRect(rect) if let layoutInfo = self.layoutInfo { attributes?.append(layoutInfo) } return attributes } the warning message is Variable 'attributes' was never mutated, consider changing to 'let' constant Why does xcode say Variable

What's the difference between if nil != optional … and if let _ = optional …

你离开我真会死。 提交于 2019-12-18 03:05:41
问题 I need to test if an expression which returns an optional is nil . This seems like a no-brainer, but here is the code. if nil != self?.checklists.itemPassingTest({ $0 === note.object }) { … } Which, for some reason, looks unpleasant to my eye. if let item = self?.checklists.itemPassingTest({ $0 === note.object }) { … } Looks much better to me, but I don't actually need the item, I just need to know if one was returned. So, I used the following. if let _ = self?.checklists.itemPassingTest({ $0

Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

自古美人都是妖i 提交于 2019-12-18 02:47:10
问题 Consider the usage of this expression: String hi = Optional.ofNullable(sayHi()).orElse("-"); which effectively corresponds to this ternary expression: String hi = sayHi() != null ? sayHi() : "-"; Is this usage of Optional.ofNullable with a method call a good practice? Or just extra verbose coding? I recognise that Optional.ofNullable actually creates a variable and avoids calling the sayHi() method twice. To avoid this problem you actually could create an extra variable but this adds to the

Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

这一生的挚爱 提交于 2019-12-18 02:47:08
问题 Consider the usage of this expression: String hi = Optional.ofNullable(sayHi()).orElse("-"); which effectively corresponds to this ternary expression: String hi = sayHi() != null ? sayHi() : "-"; Is this usage of Optional.ofNullable with a method call a good practice? Or just extra verbose coding? I recognise that Optional.ofNullable actually creates a variable and avoids calling the sayHi() method twice. To avoid this problem you actually could create an extra variable but this adds to the

Using '!' here is deprecated and will be removed in a future release - swift 4.2

大城市里の小女人 提交于 2019-12-17 21:29:19
问题 Compiler throwing following warning when setting image in a cell using SDWebimage in Swift 4.2. Swift Compiler warning : Using '!' here is deprecated and will be removed in a future release let url = NSURL(string: (str_url) as String) cell.img!.sd_setImage(with: url as URL!, completed: block_image) //--- WARNING ON THIS LINE AT URL! Any Suggestions ? 回答1: Use this code : cell. img!.sd_setImage(with: url! as URL, completed: block_image) Suggestion: use URL instead of NSURL let url = URL(string

Why can't Swift's greater-than or less-than operators compare optionals when the equality operators can?

徘徊边缘 提交于 2019-12-17 20:52:56
问题 In Swift 3, this is a compile error, if I use > or < let a: Int? guard a > 0 else {return} guard a < 0 else {return} Compile error: Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'? But it's okay if I compare with == or != let a: Int? guard a == 0 else {return} guard a != 0 else {return} 回答1: It makes perfect sense for the equality operator to support optionals, because it's absolutely clear that for any integer valued variable i : nil == nil nil != i i != nil i ==

Why does `Option` support `IntoIterator`?

扶醉桌前 提交于 2019-12-17 20:43:38
问题 I was trying to iterate over a subsection of a vector of strings, i.e. a subslice of Vec<String> . Within each iteration, I wanted to pass the string as a slice to a function. I didn't notice that Vec::get returns an Option , and thought I could just directly iterate over the return value: fn take_str(s: &str) { println!("{}", s); } fn main() { let str_vec: Vec<String> = ["one", "two", "three", "uno", "dos", "tres"].iter().map(|&s| s.into()).collect(); for s in str_vec.get(0..3) { take_str(&s