Swift 困ったところメモ


気にとめた箇所を随時更新します。

# swiftでCoreDataを利用する場合、Entityのクラス名には、ネームスペースとしてProjectNameを付ける(2015/6/21)

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html#//apple_ref/doc/uid/TP40014216-CH5-ID86

http://qiita.com/mokemokechicken/items/9cb875cc4143947fcc06

http://stackoverflow.com/questions/24662780/swift-cannot-test-core-data-in-xcode-tests

# クラスに比較演算を追加する(2015/6/21)

http://stackoverflow.com/questions/24334684/how-do-i-implement-swifts-comparable-protocol

```swift

extensino Address Comparable {
}

func <(lhs:Address, rhs:Address) -> Bool {
    return lhs.address < rhs.address
}

func ==(lhs:Address, rhs:Address) -> Bool {
    return lhs.address == rhs.address
}
```

# 静的にクラスのクラスオブジェクトを参照する方法(2015/6/21)

```Swift

let cls = Address.self

```

# 動的にインスタンスのクラスオブジェクトを参照する方法(2015/6/21)

```Swift
let cls = obj.dynamicType
```

# String.Indexの生成方法(2015/6/21)

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

```Swift

var str = "ABC"
str.startIndex // location:A
str.startIndex.successor() // location:B
advance(str.startIndex, 2) // location:C

```

http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift

# 弱参照オブジェクトをコレクションに格納したい.(2015/6/21)

http://stackoverflow.com/questions/24127587/how-do-i-declare-an-array-of-weak-references-in-swift

```Swift

class Weak<T:AnyObject> : NSObject {
    
    weak var value: T!
    
    init(value:T!)  {
        super.init()
        self.value = value
    }
}
```

```Swift

var objectMap:[NSObject:AnyObject]()

public func setObject(object:AnyObject, key:NSObject) {
    self.objectMap[key] = Weak(value: object)
}
```

# NSBundle.bundleForClass(2015/6/21)

```Swift

class AAA : NSObject {

  func aaa() {
    var bundle = NSBundle(forClass:self.dynamicType)
  }
  
}
```

# Swiftにヒアドキュメントは無い.(2015/6/21)

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

# NSReguarExpressionでは、名前付きキャプチャを利用する事ができない？(2015/6/21)

https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html

# 定義したメソッドの引数でNSErrorPointerを利用する(2015/6/21)

http://www.kuma-de.com/blog/2015-01-24/6884

```swift
TODO:追加
```

# String <-> UnsafePointer(2015/6/22)

 http://stackoverflow.com/questions/24418955/working-with-c-strings-in-swift-or-how-to-convert-unsafepointercchar-to-cstr

```swift

var s1 = "ABC"
let s2 = strdup(s1) // UnsafePointer<CChar>
let s3 = String.fromCString(s2) // String

```

```swift

init(queueName:String) {
  self.sendQueue = dispatch_queue_create(strdup(queueName), nil)
}
```


# String <-> UnsafeMutablePointer\<NSString?\> (2015/6/22)

```swift

func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {

  var host:NSString?
  var port:UInt16

  // GCDAsyncUdpSocket.getHost(hostPtr: AutoreleasingUnsafeMutablePointer<NSString?>, port: UnsafeMutablePointer<UInt16>, fromAddress: NSData!)
  
  GCDAsyncUdpSocket.getHost(&host, port: &port, fromAddress: data)
}
```

# ビットマスクとして定義されたenum値を利用するには(2015/6/23)

http://nshipster.com/rawoptionsettype/

```swift
let a = NSStringCompareOptions.RegularExpressionSearch | .WidthInsensitiveSearch
XCTAssertEqual(NSStringCompareOptions.RegularExpressionSearch, a & .RegularExpressionSearch)
XCTAssertEqual(NSStringCompareOptions.WidthInsensitiveSearch, a & .WidthInsensitiveSearch)
XCTAssertTrue(a & .RegularExpressionSearch != nil)
XCTAssertTrue(a & .WidthInsensitiveSearch != nil)
XCTAssertEqual(nil, a & .CaseInsensitiveSearch)
```


NSStringCompareOptionsのコード

```swift
/* These options apply to the various search/find and comparison methods (except where noted).
*/
struct NSStringCompareOptions : RawOptionSetType {
    init(_ rawValue: UInt)
    init(rawValue: UInt)
    
    static var CaseInsensitiveSearch: NSStringCompareOptions { get }
    static var LiteralSearch: NSStringCompareOptions { get } /* Exact character-by-character equivalence */
    static var BackwardsSearch: NSStringCompareOptions { get } /* Search from end of source string */
    static var AnchoredSearch: NSStringCompareOptions { get } /* Search is limited to start (or end, if NSBackwardsSearch) of source string */
    static var NumericSearch: NSStringCompareOptions { get } /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */
    @availability(iOS, introduced=2.0)
    static var DiacriticInsensitiveSearch: NSStringCompareOptions { get } /* If specified, ignores diacritics (o-umlaut == o) */
    @availability(iOS, introduced=2.0)
    static var WidthInsensitiveSearch: NSStringCompareOptions { get } /* If specified, ignores width differences ('a' == UFF41) */
    @availability(iOS, introduced=2.0)
    static var ForcedOrderingSearch: NSStringCompareOptions { get } /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */
    @availability(iOS, introduced=3.2)
    static var RegularExpressionSearch: NSStringCompareOptions { get } /* Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */
}
```




```swift

/// Protocol for `NS_OPTIONS` imported from Objective-C
protocol RawOptionSetType : _RawOptionSetType, BitwiseOperationsType, NilLiteralConvertible {
}

protocol BitwiseOperationsType {

    /// Returns the intersection of bits set in `lhs` and `rhs`.
    ///
    /// Complexity: O(1)
    func &(lhs: Self, rhs: Self) -> Self

    /// Returns the union of bits set in `lhs` and `rhs`
    ///
    /// Complexity: O(1)
    func |(lhs: Self, rhs: Self) -> Self

    /// Returns the bits that are set in exactly one of `lhs` and `rhs`
    ///
    /// Complexity: O(1)
    func ^(lhs: Self, rhs: Self) -> Self

    /// Returns `x ^ ~Self.allZeros`
    ///
    /// Complexity: O(1)
    prefix func ~(x: Self) -> Self

    /// The empty bitset.
    ///
    /// Also the `identity element
    /// <http://en.wikipedia.org/wiki/Identity_element>`_ for `|` and
    /// `^`, and the `fixed point
    /// <http://en.wikipedia.org/wiki/Fixed_point_(mathematics)>`_ for
    /// `&`.
    static var allZeros: Self { get }
}
```

# if文で範囲チェック(2015/7/1)

0 <= index < length

```swift

  if 0 ..< length ~= index {
  }

```

0 <= index <= length

```swift
  if 0 ... length ~= index {
  }
```

下記stackoverflowによるとswift2では変わるっぽい。

http://stackoverflow.com/questions/24893110/can-i-use-the-range-operator-with-if-statement-in-swift

# ログに関数名を出力したい(2015/7/21)

println(\_\_FUNCTION\_\_)

|Literal|Type|Value|
|:------|:---|:----|
|\_\_FILE\_\_|String|The name of the file in which it appears.|
|\_\_LINE\_\_|Int|The line number on which it appears.|
|\_\_COLUMN\_\_|Int|The column number in which it begins.|
|\_\_FUNCTION\_\_|String|The name of the declaration in which it appears.|



参考: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/swift/grammar/expression