2015-10-17 18 views
2

我知道這是可能做到這一點,像這樣:只有在一個表達式中的可選項不爲零時才調用函數?

let intValue: Int? = rawValue == nil ? Int(rawValue) : nil 

甚至是這樣的:

var intValue: Int? 

if let unwrappedRawValue = rawValue { 
    intValue = Int(unwrappedRawValue) 
} 

但是我正在尋找,以找出是否有辦法在一個表達式做到這一點,像這樣:

let intValue: Int? = Int(rawValue) // Where Int() is called only if rawValue is not nil 
+0

? – Korpel

+0

如果'rawValue'不是零,我想'intValue'是'Int(rawValue)',否則如果'rawValue'是零我希望'intValue'是零。 –

+0

如果您確定它不是零但是您的兩種方式可以完成他們的工作,您可以明確地解開它。請問你到底在做什麼?或者這是一個通用的問題? – Korpel

回答

-2

因此,爲了回答你的問題,在這裏你可以有一些可選的情況如下: 你的第一個:

let intValue: Int? = rawValue == nil ? Int(rawValue) : nil 

你的第二個:

var intValue: Int? 

if let unwrappedRawValue = rawValue { 
    intValue = Int(unwrappedRawValue) 
} 

第三種情況:

var intValue : Int? 
if intValue !=nil 
{ 
//do something 
} 

第四種情況,如果你是肯定的值不爲零

var intValue : Int? 
intValue! 

最後一種情況會如果價值爲零,應用程序會崩潰您將來可能會將其用於調試目的。我建議你從蘋果公司的手冊上可選的結合和可選的鏈接這些鏈接看看

optional Chaining

full apple guide for swift

,並回答您的評論部分的問題,以完成大部分開發人員傾向於使用這種方法:

var intValue: Int? 

if let unwrappedRawValue = rawValue { 
    intValue = Int(unwrappedRawValue) 
} 

因爲它似乎是最安全的類型。你的來電。

2

同樣爲Getting the count of an optional array as a string, or nil,您可以使用Optionalmap() 方法:

/// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`. 
@warn_unused_result 
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U? 

例子:

func foo(rawValue : UInt32?) -> Int? { 
    return rawValue.map { Int($0) } 
} 

foo(nil) // nil 
foo(123) // 123 
你想,如果是的intValue不爲零與rawValue分配
相關問題