swift學習第七天 ?和!
阿新 • • 發佈:2018-12-25
Swift語言使用var定義變數,但和別的語言不同,Swift裡不會自動給變數賦初始值,也就是說變數不會有預設值,所以要求使用變數之前必須要對其初始化。如果在使用變數之前不進行初始化就會報錯:
- var stringValue : String
- //error: variable 'stringValue' used before being initialized
- //let hashValue = stringValue.hashValue
- // ^
- let hashValue = stringValue.hashValue
- enum
- case None
- case Some(T)
- init()
- init(_ some: T)
- /// Allow use in a Boolean context.
- func getLogicValue() -> Bool
- /// Haskell's fmap, which was mis-named
- func map<U>(f: (T) -> U) -> U?
- func getMirror() -> Mirror
- }
- var strValue : String?
- if strValue {
- //do sth with strValue
- }
- let hashValue = strValue?.hashValue
- //error: 'String?' does not have a member named 'hashValue'
- //let hashValue = strValue.hashValue
- // ^ ~~~~~~~~~
- let hashValue = strValue.hashValue
- if let str = strValue {
- let hashValue = str.hashValue
- }
- let hashValue = strValue!.hashValue
- if strValue {
- let hashValue = strValue!.hashValue
- }
- myLabel!.text = "text"
- myLabel!.frame = CGRectMake(0, 0, 10, 10)
- ...