Swift UITextChecker - xcode

I am trying to use UITextChecker in my Swift project. The code below currently has an error on the last line:
var checker:UITextChecker = UITextChecker()
var textLength = countElements(textView.text)
var checkRange:NSRange = NSMakeRange(0, textLength)
var misspelledRange:NSRange = checker.rangeOfMisspelledWordInString(textView.text, range: checkRange, startingAt: checkRange.location, wrap: false, language: "en_Us")
var arrGuessed:NSArray = checker.guessesForWordRange(misspelledRange, inString: textView.text, language: "en_US")!
var correctedStr = textView.text.stringByReplacingCharactersInRange(misspelledRange, withString: [arrGuessed.objectAtIndex(0)])
The error says:
'NSRange' is not convertible to 'Range<String.index>'
I am not sure where I am going wrong.
Thanks

The stringByReplacingCharactersInRange method you're using expects Range<String.Index> to be passed in, not NSRange. You can't use misspelledRange because it's the wrong type. The link in the possible duplicate comment (NSRange to Range<String.Index>) has examples of deriving a Range<String.Index> from an NSRange or casting text to NSString, whose stringByReplacingCharactersInRange method does use NSRange.

Related

Swift Error: Cannot find an initializer for type 'Double' that accepts an argument list of type '(String)'

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())"

HIDictionaryWindowShow usage in Swift

How do you invoke HIDictionaryWindowShow in Swift? I try this:
import Carbon
if let text = _dictionaryText, let range = _dictionaryRange
{
let font = CTFontCreateWithName("Baskerville", 16, nil);
let point = CGPoint(x: 0.0, y: 0.0);
var trns = CGAffineTransform();
HIDictionaryWindowShow(nil, text, range, font, point, false, &trns);
}
But getting error
Cannot invoke 'HIDictionaryWindowShow' with an argument list of type
'(nil, String, CFRange, CTFont!, CGPoint, Bool, CGAffineTransform)'
Not seeing the wrong argument here. First and last argument should be allowed to be nil but docs say that NULL is Ok as the first argument which is nil in Swift or is it? As there is no NULL in Swift what do I need to specify instead of it?
Sorry I don't have the Swift code, but you can probably work from the following untested objective-c code. Note that showDefinitionForAttributedString was added to replace HIDictionaryWindowShow which is, as you know, a carbon function and won't be supported forever.
[self.view showDefinitionForAttributedString:[[NSAttributedString alloc] initWithString:text] atPoint:NSMakePoint(0.0, 0.0)];
EDIT:
In looking further the second argument is not correct in your example. Carbon lib does not understand String, it wants CFTypeRef.

Strange error when adding UIFont to styling dictionary (NSAttributedString) [duplicate]

let timeFont = [NSFontAttributeName:UIFont(name: "Voyage", size: 20.0)]
var attrString3 = NSAttributedString("(Time)", attributes : timeFont); // <--- compiler error "Extra argument in call"
This code worked in xcode 6.0, but now that I've upgraded to xcode 6.1 it doesn't work anymore and I can't figure out what I need to get it back working. It says that there is an extra argument, but that's not correct. I believe that it has something to do with the new failable initializers, but everything that I've tried doesn't' work.
There are two reasons your code is failing to compile:
The initializer for NSAttributedString that you want to use now requires the explicit labeling of the string parameter
The UIFont initializer that you are using now returns an optional (i.e., UIFont?), which needs to be unwrapped before you pass it in the attributes dictionary.
Try this instead:
let font = UIFont(name: "Voyage", size: 20.0) ?? UIFont.systemFontOfSize(20.0)
let attrs = [NSFontAttributeName : font]
var attrString3 = NSAttributedString(string: "(Time)", attributes: attrs)
Note the use of the new coalescing operator ??. This unwraps the optional Voyage font, but falls back to the System Font if Voyage is unavailable (which seems to be the case in the Playground). This way, you get your attributed string regardless, even if your preferred font can't be loaded.
Xcode 6.1 comes with Swift 1.1 that supports constructors that can fail. UIFont initialisation can fail and return nil. Also use string: when creating NSAttributedString:
if let font = UIFont(name: "Voyage", size: 20.0) {
let timeFont = [NSFontAttributeName:font]
var attrString3 = NSAttributedString(string: "(Time)", attributes : timeFont)
}

TTTAttributedLabel addLinkToURL NSRange confusion

I am making a swift app and I want to add a url to a TTTAttributedLabel. I have got addLinkToUrl but it wants a NSRange. What should I put. I am new to swift. I want the url to be for the entire text.
//PersonTalking is a TTTAttributedLabel
var characterSpeaking:NSDictionary = item["characterspeaking"] as NSDictionary
var characterSpeakingString:String = characterSpeaking["text"] as String
var characterHref:String = characterSpeaking["href"] as String
var characterUrl = NSURL(string: characterHref)
println(characterSpeakingString)
PersonTalking.text = characterSpeakingString
PersonTalking.addLinkToURL(characterUrl, withRange: )
What can I do?
Thanks
If the link is meant to include the full label, then your range should be the full length of your text.
PersonTalking.addLinkToURL(characterUrl,
withRange:NSMakeRange(0,
countElements(characterSpeakingString))

Xcode 6.1.1 Swift returns "Optional("$1234.12")" with formatter

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)!)")

Resources