I am getting below error during Objective-C to Swift code change. Thanks
func combinedName() -> String? {
let range: NSRange = name.range(of: brand)
if Int(range.length) > 0 {
return name
}
return "\(brand) \(name)"
}
My Objective-C code
- (NSString *)combinedName {
NSRange range = [self.name rangeOfString:self.brand];
if (range.length > 0) return self.name;
return [NSString stringWithFormat:@"%@ %@", self.brand, self.name];
}
Don't directly translate Objective-C code. Write it from scratch as Swift code using normal Swift constructs.
func combinedName() -> String {
if name.range(of: brand) != nil {
return name
} else {
return "\(brand) \(name)"
}
}
Assuming both name
and brand
are not optional, the return type shouldn't be optional because you don't return nil
under any circumstances.
You can also make the code simpler using ?:
:
func combinedName() -> String {
return name.range(of: brand) != nil ? name : "\(brand) \(name)"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.