LoginSignup
39
39

More than 5 years have passed since last update.

Swift 困ったところメモ

Last updated at Posted at 2015-06-21

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

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

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


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)


let cls = Address.self

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

let cls = obj.dynamicType

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


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

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


class Weak<T:AnyObject> : NSObject {

    weak var value: T!

    init(value:T!)  {
        super.init()
        self.value = value
    }
}

var objectMap:[NSObject:AnyObject]()

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

NSBundle.bundleForClass(2015/6/21)


class AAA : NSObject {

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

}

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

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

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

TODO:追加

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


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


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

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


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)

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のコード

/* 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 */
}

/// 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


  if 0 ..< length ~= index {
  }

0 <= index <= length

  if 0 ... length ~= index {
  }

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

ログに関数名を出力したい(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

39
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
39