ios - Xcode 7 beta 2 and swift not getting along -
i have error when typed in code, gave me error. looks perfect, here code:
import uikit class secondviewcontroller: uiviewcontroller { @iboutlet weak var resultlabel: uilabel! @iboutlet weak var temptext1: uitextfield! @ibaction func converttemp1(sender: anyobject) { #let fahrenheit = (temptext1.text nsstring).doublevalue let celsius = (fahrenheit - 32 )/1.8 let resulttext = "celsius \(celsius)" resultlabel.text = resulttext } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } }
it give me following error: 'string?' not convertable 'nsstring' on line put # on. # not in real code.
note: not understand computer talk please try speak simply. :)
the text property of uitextfield returns optional string code doesn't handle optionals. casting nsstring isn't allowed there (also not necessary doublevalue).
you need handle optional. force-unwrap using !
. can lead crashes. better use if let
or guard let
statements:
guard let fahrenheit = temptext1.text?.doublevalue else { return }
for conciseness use optional chaining (the ?
here). keep in 2 steps:
guard let fahrenheitstring = temptext1.text else { return } let fahrenheit = fahrenheitstring.doublevalue
both equivalent.
Comments
Post a Comment