Swift手册第61页的Swift文档提示可以使用where常规条件连接可选绑定.然而,当我这样做时,我有一个警告,建议我where用以下代码中的逗号替换:
if let geocodingError = error as? NSError where geocodingError.code == 2
Run Code Online (Sandbox Code Playgroud) 我知道我可以用Swift检查var的类型 is
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
Run Code Online (Sandbox Code Playgroud)
但是如何检查两个实例是否具有相同的类?以下不起作用:
if item1 is item2.dynamicType {
print("Same subclass")
} else {
print("Different subclass)
}
Run Code Online (Sandbox Code Playgroud)
我可以轻松地添加一个"类"函数并在每个子类中更新它以返回一些独特的东西,但这看起来像一个kludge ...
尝试使用Equatable协议中定义的'=='运算符比较AnyObject类型的两个对象会导致Swift中出现编译错误.有没有人找到比较这些对象的方法,而不知道可以用于向下转换的真实对象类型?
这个问题的背景是我有一个字典Dictionary <String,AnyObject>,其中值应该通过下标提供,然后在某些时候我需要比较字典中的值以确保它们是唯一的.
编辑 这是一个演示该问题的片段.
@objc(FooObject)
public class FooObject: NSManagedObject {
@NSManaged public var properties: Dictionary<String, AnyObject>
public subscript(property: String) -> AnyObject? {
get {
return properties[property]
}
set(newValue) {
for propertyValue in properties.values {
if propertyValue == newValue { // This line is not compiling: Cannot invoke '==' with AnyObject
println("Values in are expected to be unique!")
// Throw an exception here ...
}
}
properties[property] = newValue
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在类定义中声明的类似<T:Equatable>的泛型并用作字典的值类型将无法解决问题,因为它不能与NSManagedObject子类一起使用.
我创建了一个示例项目和旁边的框架.该框架称为"SampleFramework".然后我在SampleFramework中创建了一个自定义运算符.这是它的样子:
infix operator >>= {associativity left}
public func >>=<A, B>(a: A?, f: A -> B?) -> B? {
if let a = a { return f(a) }
else { return .None }
}
Run Code Online (Sandbox Code Playgroud)
然后我想用它作为我的主要应用程序.我导入了SampleFramework我的源文件,然后我编写了这段代码来测试它:
NSURL(string: "www.google.com") >>= { println("\($0)") }
Run Code Online (Sandbox Code Playgroud)
它没有编译.这是Xcode的错误消息:
为运营商找到不明确的运营商声明.运算符不是已知的二元运算符
我有以下简单的扩展Double,在Xcode 8 beta 3的所有功能都可以正常工作
public extension Double {
public func roundTo(_ decimalPlaces: Int) -> Double {
var v = self
var divisor = 1.0
if decimalPlaces > 0 {
for _ in 1 ... decimalPlaces {
v *= 10.0
divisor *= 0.1
}
}
return round(v) * divisor
}
}
Run Code Online (Sandbox Code Playgroud)
从Beta 4开始,我得到"不能在变量值上使用变异成员:'self'是不可变的"在round返回函数中 - 有没有人有任何线索?
我正在浏览Alamofire源代码,并发现变量的哪个名称在此源文件中被反引号转义
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
Run Code Online (Sandbox Code Playgroud)
但是在使用变量的地方没有反引号.反叛的目的是什么?
在Swift 1.2中我有这个:
if let filePath = NSBundle.mainBundle().pathForResource("some", ofType: "txt"),
data = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) {
for line in data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) {
// Do something
}
} else {
println("some.txt is missing")
}
Run Code Online (Sandbox Code Playgroud)
在斯威夫特2,我再也不能这样做,因为这两个pathForResource和contentsOfFile可以抛出,以及返回自选.我可以解决它,但它现在看起来非常冗长:
do {
if let filePath = try NSBundle.... {
do {
if let data = try String.... {
for line in data..... {
// Do something
}
} else {
print("Nil data")
}
} catch {
print("contentsOfFile threw")
}
} else {
print("Nil …Run Code Online (Sandbox Code Playgroud) 我正在尝试子类化MKPolyline并MKGeodesicPolyline存储他们自己的颜色(通过让子类实例返回自己的颜色MKPolylineRenderer).它工作正常MKPolyline,但我的MKGeodesicPolyline子类的实例不是子类 - 只是MKGeodesicPolylines.有谁能解释为什么?这是我的代码......
protocol MapLineProtocol: MKOverlay {
var width: CGFloat { get set }
var colour: UIColor { get set }
}
extension MapLineProtocol {
var renderer: MKPolylineRenderer {
let polylineRenderer = MKPolylineRenderer(overlay: self)
polylineRenderer.strokeColor = self.colour
polylineRenderer.lineWidth = self.width
return polylineRenderer
}
}
class MapLine: MKPolyline, MapLineProtocol {
var width: CGFloat = 3
var colour: UIColor = .blue
convenience init(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D) {
let line …Run Code Online (Sandbox Code Playgroud) 我曾经在我的类NSObject构造函数中使用以下代码使用Objective-c:
- (id)init {
self = [super init] ;
return self;
}
Run Code Online (Sandbox Code Playgroud)
我如何在Swift中使用它?
我试着这样做:
override init() {
self = super.init()
return self;
}
Run Code Online (Sandbox Code Playgroud)
我有两个错误:
cannot assign value self is immutable
nil is the only return value permitted in this initializer
Run Code Online (Sandbox Code Playgroud) 今天,当我试图"概括"我的'CoreData导入操作'时,我遇到了一个奇怪的问题.似乎如果我创建NSOperation的泛型子类,main()则不会调用func.
简单的例子:
class MyOperation<T: NSObject>: NSOperation {
override func main() {
println("My operation main was called")
}
}
Run Code Online (Sandbox Code Playgroud)
如果您创建此类的实例并将其添加到operationQueue您将看到它main()实际上没有被调用.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.operationQueue = NSOperationQueue()
let operation = MyOperation<NSString>()
self.operationQueue!.addOperation(operation)
}
Run Code Online (Sandbox Code Playgroud)
操作简单地从过境ready到executing和finished状态,而无需调用main().
如果我<T: NSObject>从MyOperation类中删除泛型注释,它将正常工作.
这怎么可能?我在这里错过了什么吗?
swift ×9
ios ×3
swift3 ×2
alamofire ×1
comparison ×1
generics ×1
mapkit ×1
nsoperation ×1
objective-c ×1
operators ×1
optional ×1
where ×1