Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

swift How to determine if a variable is an optional

I want to know if a variable is an optional

I try method below, but fail

func isOptional(v: Any) -> Bool {
    return v is Optional
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an academic exercise (can it be done vs. should it be done), I came up with this:

func isOptional(a: Any) -> Bool {
    return "(a.dynamicType)".hasPrefix("Swift.Optional")
}

Example:

let name = "Fred"
let oname: String? = "Jones"
let age = 37
let oage: Int? = 38

let arr: [Any] = [name, oname, age, oage]

for item in arr {
    println("(item) (isOptional(item))")
}

Output:

Fred false
Optional("Jones") true
37 false
Optional(38) true

Would I recommend using this in production code? No. I recommend staying away from Any if at all possible, and I wouldn't bet on the output of dynamicType remaining the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...