I was doing a playground to check swift 2.0 and this happens:
I do not know if im missing something, or is this normal or what? Thanks.
In swift 1.2 is working as expected XCode 6.3.
EDIT: Code
//: Playground - noun: a place where people can play
import Foundation
var str = "Hello, playground"
let languageType: String = "Swift"
var version = 1.0 //infered
let introduced = 2014 //infered
let isAwesome = true //infered
let π = 3.1415927
let 🐶🐮 = "dogcow"
let someString = "I appear to be a string"
let pathComponent = "~/Documents/Swift".pathComponents
var s = String("bla vla nla")
for character in "catDog" {
print(character)
}
the API for String has changed in Swift 2, to accomplish what it looks like you are trying to do, you would instead use for character in "catDog".characters {...}
an excellent reference is Nate Cook's swiftdoc.org
Related
Im doing a watch app for the Apple Watch in Xcode and the sample code from the Apple Developer site SpeedySloth: Creating a Workout has the HeartRate rounded to one decimal place, e.g. 61.0
How can I fix this?
case HKQuantityType.quantityType(forIdentifier: .heartRate):
/// - Tag: SetLabel
let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
let value = statistics.mostRecentQuantity()?.doubleValue(for: heartRateUnit)
let roundedValue = Double( round( 1 * value! ) / 1 )
label.setText("\(roundedValue) BPM")
I tried changing both the 1's in there to 0 but that gave me a 6.1 BPM or a 0.0 BPM
Thanks
A simple solution is to round to an integer and show the integer.
let value = // ... some Double ...
let s = String(Int(value.rounded(.toNearestOrAwayFromZero)))
label.setText(s + " BPM")
Properly, however, you should put formatting a string based on a number into the hands of a NumberFormatter. That's its job: to format a number.
let i = value.rounded(.toNearestOrAwayFromZero)
let nf = NumberFormatter()
nf.numberStyle = .none
let s = nf.string(from: i as NSNumber)!
// ... and now show the string
So this worked flawlessly in Swift 2 but in Swift 3 it has problems:
func myNotifications () {
let interval = 2.0
var daysOut = 2.0
let myArray =getArray()
for i in 0..<myArray.count {
let message = ("\(myArray[i])\n-\(myArray[i])")
let localNotification = UILocalNotification()
localNotification.fireDate = Date(timeIntervalSinceNow: (60*60*24*daysOut))
localNotification.alertBody = message
localNotification.timeZone = NSTimeZone.autoupdatingCurrent
localNotification.category = "Message"
UIApplication.shared.scheduleLocalNotification(localNotification)
daysOut += interval
}
let arrayCount = Double(myArray.count)
let lastNotif_Date = Date(timeIntervalSinceNow: (60*60*24*interval*(quoteCount+1)))
userPref_NSDefault.set(lastNotif_Date, forKey: "notification_EndDate")
}
Specifically, this line no longer works which is a big deal because I have users in multiple timezones and I want to make sure this works:
localNotification.timeZone = NSTimeZone.autoupdatingCurrent
I get the error message:
Type "NSTimeZone" has no member "autoUpdatingCurrent"
Any ideas? I tried "timeZone.automatic", ".automatic", and some other variations but haven't been able to figure it out.
autoupdatingCurrent != autoupdatingCurrent
NSTimeZone has been renamed to TimeZone
I am trying to grab data from a text field labeled 'temperatureTextField' and assigning it to 't' which is a Double. Ideally the user is meant to add a number value to the temperatureTextField.
Here is my method:
#IBOutlet weak var temperatureTextField: UITextField!
#IBAction func convert(sender: AnyObject) {
let t = Double(temperatureTextField.text!)
let tempM = TemperatureModel(temp: t!)
temperatureTextField.text = String(tempM.toCelsius())
}
The red exclamation is coming from the line "let t = Double(temperatureTex...)"
You're probably using Xcode 6, so Swift 1.2, but the String initializer for Double is only available in Swift 2 (Xcode 7).
You can always use NSString's doubleValue property:
let t = (temperatureTextField.text! as NSString).doubleValue
but I'd recommend using Xcode 7 and Swift 2 as soon as possible.
As Eric suggested, I ran into this issue because I was running an outdated version of xcode.
Here is what my code looked liked after, in case anyone runs into trouble and is unable to update:
let t = (inputText.text! as NSString).doubleValue
let tempModel = TemperatureModel(temp: t)
inputText.text = "\(tempModel.toCelsius())"
I am using swift2.
I used this code:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitMonth | .CalendarUnitDay, fromDate: theDate)
I am getting this error: Could not find member 'CalendarUnitMonth'
Check Swift 2 documentation and search for OptionSetType (adopted by NSCalendarUnit). You can use it in this way:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Month, .Day], fromDate:NSDate())
i'm just in playground trying to get this thing to work, but it doesn't want to work for me..
var total = 1234.1234
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
println("\(formatter.stringFromNumber(total))")
// Returns: "Optional("$1,234.12")" instead of just "$1,234.12"
I want to show just the formatted number to the user but the extra Optional bit keeps showing up.
Since you're just in playgrounds and are sure that the optional contains a value,
you can use forced unwrappping by adding an exclamation mark:
print("\(formatter.stringFromNumber(total)!)")